Example #1
0
def test_craft_response_attachment():
    sample = MailResponse(To=list_name + "@librelist.com",
                          From=user_full_address,
                          Subject="Test message with attachments.",
                          Body="The body as one attachment.")

    sample.attach(filename="tests/model/mailinglist_tests.py",
                  content_type="text/plain",
                  disposition="attachment")

    sample['message-id'] = '123545666'

    im = sample.to_message()
    assert_equal(len([x for x in im.walk()]), 3)
    
    inmsg = MailRequest("fakepeer", None, None, str(sample))
    assert_equal(len(inmsg.all_parts()), 2)

    outmsg = craft_response(inmsg, list_name, list_name +
                                        "@librelist.com")
  
    om = outmsg.to_message()

    assert_equal(len([x for x in om.walk()]),
                 len([x for x in im.walk()]))

    assert 'message-id' in outmsg
Example #2
0
def handle_reply(message, group_name=None, thread_id=None, msg_id=None, suffix=None, host=None):
	name, addr = parseaddr(message['from'].lower())
	msg_id = msg_id.lower()
	group_name = group_name.lower()
	msg_text = get_body(str(message))
	res = insert_reply(group_name, message['Subject'], msg_text['body'], addr, msg_id, thread_id)
	if(not res['status']):
		mail = MailResponse(From = NO_REPLY, To = addr, Subject = "Error", Body = "Error Message:%s" %(res['code']))
		relay.deliver(mail)
		return
	msg_id = res['msg_id']
	to_send =  res['recipients']
	post_addr = '%s <%s>' %(group_name, group_name + '+' + str(thread_id) + '+' + str(msg_id) + POST_SUFFIX + '@' + host)
	mail = MailResponse(From = message['From'], To = post_addr, Subject = message['Subject'])
	
	if 'references' in message:
		mail['References'] = message['References']
	elif 'message-id' in message:
		mail['References'] = message['message-id']

	
	mail['message-id'] = msg_id
	
	ps_blurb = html_ps(thread_id, msg_id, group_name, host)
	mail.Html = unicode(msg_text['body'] + ps_blurb , "utf-8")
	logging.debug('TO LIST: ' + str(to_send))
	if(len(to_send) > 0):
		relay.deliver(mail, To = to_send)
Example #3
0
def insert_reply(request):
	try:
		group_name = request.POST['group_name'].encode('ascii', 'ignore')
		subject = request.POST['subject'].encode('ascii', 'ignore')
		msg_text = request.POST['msg_text'].encode('ascii', 'ignore')
		msg_id = request.POST['msg_id'].encode('ascii', 'ignore')
		thread_id = request.POST['thread_id'].encode('ascii', 'ignore')
		poster_email = request.POST['poster_email'].encode('ascii', 'ignore')
		res = engine.main.insert_reply(group_name, subject, msg_text, poster_email, msg_id, thread_id)
		res.update({'user': request.session[SESSION_KEY]})
		if(res['status']):
			new_msg_id = res['msg_id']
			thread_id = res['thread_id']
			to_send =  res['recipients']
			post_addr = '%s <%s>' %(group_name, group_name + '+' + str(thread_id) + '+' + str(new_msg_id) + POST_SUFFIX + '@' + HOST)
			mail = MailResponse(From = poster_email, To = post_addr, Subject  = '%s' %(subject))
			
			
			mail['References'] = msg_id		
			mail['message-id'] = new_msg_id
				
			ps_blurb = html_ps(thread_id, msg_id, group_name, HOST)
			mail.Html = msg_text + ps_blurb		
			logging.debug('TO LIST: ' + str(to_send))
			if(len(to_send)>0):
				relay_mailer.deliver(mail, To = to_send)
		return HttpResponse(json.dumps(res), mimetype="application/json")
	except Exception, e:
		print sys.exc_info()
		logging.debug(e)
		return HttpResponse(request_error, mimetype="application/json")
Example #4
0
def handle_post(message, address=None, host=None):
	address = address.lower()
	name, addr = parseaddr(message['From'].lower())
	reserved = filter(lambda x: address.endswith(x), RESERVED)
	if(reserved):
		return
	group_name = address.lower()
	subject = '[ %s ] -- %s' %(group_name, message['Subject'].encode('ascii', 'ignore'))
	msg_text = get_body(str(message))
	res = insert_post(group_name, subject, msg_text['body'], addr)
	if(not res['status']):
		mail = MailResponse(From = NO_REPLY, To = addr, Subject = "Error", Body = "Error Message:%s" %(res['code']))
		relay.deliver(mail)
		return
	msg_id = res['msg_id']
	thread_id = res['thread_id']
	to_send =  res['recipients']
	post_addr = '%s <%s>' %(group_name, group_name + '+' + str(thread_id) + '+' + str(msg_id) + POST_SUFFIX + '@' + host)
	mail = MailResponse(From = message['From'], To = post_addr, Subject  = subject)
	
		
	if 'references' in message:
		mail['References'] = message['References']
	elif 'message-id' in message:
		mail['References'] = message['message-id']	
	
	
	mail['message-id'] = msg_id

	ps_blurb = html_ps(thread_id, msg_id, group_name, host)
	mail.Html = unicode(msg_text['body'] + ps_blurb , "utf-8")		
	logging.debug('TO LIST: ' + str(to_send))
	if(len(to_send)>0):
		relay.deliver(mail, To = to_send)
Example #5
0
def test_craft_response_attachment():
    sample = MailResponse(To=list_name + "@librelist.com",
                          From=user_full_address,
                          Subject="Test message with attachments.",
                          Body="The body as one attachment.")

    sample.attach(filename="tests/model/mailinglist_tests.py",
                  content_type="text/plain",
                  disposition="attachment")

    sample['message-id'] = '123545666'

    im = sample.to_message()
    assert_equal(len([x for x in im.walk()]), 3)

    inmsg = MailRequest("fakepeer", None, None, str(sample))
    assert_equal(len(inmsg.all_parts()), 2)

    outmsg = craft_response(inmsg, list_name, list_name + "@librelist.com")

    om = outmsg.to_message()

    assert_equal(len([x for x in om.walk()]), len([x for x in im.walk()]))

    assert 'message-id' in outmsg
Example #6
0
def add_members(group_name, emails, user):
	res = {'status':False}
	
	try:
		group = Group.objects.get(name=group_name)
		is_public = group.public
		is_admin = False
		if user:
			membergroup = MemberGroup.objects.get(group=group, member=user)
			is_admin = membergroup.admin
		if is_public or is_admin:
			email_list = emails.strip().lower().split(',')
			for email in email_list:
				email = email.strip()
				
				email_user = UserProfile.objects.filter(email=email)
				member = False
				if email_user.count() == 1:
					member = MemberGroup.objects.filter(member=email_user[0], group=group).exists()
				if not member:
				
					mail = MailResponse(From = 'no-reply@' + BASE_URL, 
										To = email, 
										Subject  = "You've been subscribed to %s Mailing List" % (group_name))
					
					if email_user.count() == 1:
						_ = MemberGroup.objects.get_or_create(member=email_user[0], group=group)
						
						message = "You've been subscribed to %s Mailing List. <br />" % (group_name)
						message += "To see posts from this list, visit <a href='http://%s/posts?group_name=%s'>http://%s/posts?group_name=%s</a><br />" % (BASE_URL, group_name, BASE_URL, group_name)
						message += "To manage your mailing list settings, subscribe, or unsubscribe, visit <a href='http://%s/groups/%s'>http://%s/groups/%s</a><br />" % (BASE_URL, group_name, BASE_URL, group_name)
					else:
						pw = password_generator()
						new_user = UserProfile.objects.create_user(email, pw)
						_ = MemberGroup.objects.get_or_create(group=group, member=new_user)
						
						message = "You've been subscribed to %s Mailing List. <br />" % (group_name)
						message += "An account to manage your settings has been created for you at <a href='http://%s'>http://%s</a><br />" % (BASE_URL, BASE_URL)
						message += "Your username is your email, which is %s and your auto-generated password is %s <br />" % (email, pw)
						message += "If you would like to change your password, please log in at the link above and then you can change it under your settings. <br />"
						message += "To see posts from this list, visit <a href='http://%s/posts?group_name=%s'>http://%s/posts?group_name=%s</a><br />" % (BASE_URL, group_name, BASE_URL, group_name)
						message += "To manage your mailing lists, subscribe, or unsubscribe from groups, visit <a href='http://%s/groups'>http://%s/my_groups</a><br />" % (BASE_URL, BASE_URL)
	
					mail.Html = message
					logging.debug('TO LIST: ' + str(email))
					
					relay_mailer.deliver(mail, To = [email])
			res['status'] = True
		else:
			res['code'] = msg_code['PRIVILEGE_ERROR']
	except Group.DoesNotExist:
		res['code'] = msg_code['GROUP_NOT_FOUND_ERROR']
	except MemberGroup.DoesNotExist:
		res['code'] = msg_code['NOT_MEMBER']
	except:
		res['code'] = msg_code['UNKNOWN_ERROR']
	logging.debug(res)
	return res
Example #7
0
def add_members(group_name, emails, user):
	res = {'status':False}
	
	try:
		group = Group.objects.get(name=group_name)
		membergroup = MemberGroup.objects.get(group=group, member=user)
		if membergroup.admin:
			email_list = emails.strip().lower().split(',')
			for email in email_list:
				email = email.strip()
				
				mail = MailResponse(From = 'no-reply@' + BASE_URL, 
									To = email, 
									Subject  = "You've been subscribed to %s Mailing List" % (group_name))
				
				email_user = UserProfile.objects.filter(email=email)
				if email_user.count() == 1:
					_ = MemberGroup.objects.get_or_create(member=email_user[0], group=group)
					
					message = "You've been subscribed to %s Mailing List. <br />" % (group_name)
					message += "To see posts from this list, visit <a href='http://%s/posts?group_name=%s'>http://%s/posts?group_name=%s</a><br />" % (BASE_URL, group_name, BASE_URL, group_name)
					message += "To manage your mailing list settings, subscribe, or unsubscribe, visit <a href='http://%s/groups/%s'>http://%s/groups/%s</a><br />" % (BASE_URL, group_name, BASE_URL, group_name)
				else:
					pw = password_generator()
					new_user = UserProfile.objects.create_user(email, pw)
					_ = MemberGroup.objects.get_or_create(group=group, member=new_user)
					
					message = "You've been subscribed to %s Mailing List. <br />" % (group_name)
					message += "An account has been created for you at <a href='http://%s'>http://%s</a><br />" % (BASE_URL, BASE_URL)
					message += "Your username is your email, which is %s and your auto-generated password is %s <br />" % (email, pw)
					message += "If you would like to change your password, please log in at the link above and then you can change it under your settings. <br />"
					message += "To see posts from this list, visit <a href='http://%s/posts?group_name=%s'>http://%s/posts?group_name=%s</a><br />" % (BASE_URL, group_name, BASE_URL, group_name)
					message += "To manage your mailing lists, subscribe, or unsubscribe from groups, visit <a href='http://%s/groups'>http://%s/my_groups</a><br />" % (BASE_URL, BASE_URL)

				mail.Html = message
				logging.debug('TO LIST: ' + str(email))
				
				relay_mailer.deliver(mail, To = [email])
			res['status'] = True
		else:
			res['code'] = msg_code['PRIVILEGE_ERROR']
	except Group.DoesNotExist:
		res['code'] = msg_code['GROUP_NOT_FOUND_ERROR']
	except MemberGroup.DoesNotExist:
		res['code'] = msg_code['NOT_MEMBER']
	except:
		res['code'] = msg_code['UNKNOWN_ERROR']
	logging.debug(res)
	return res
Example #8
0
def info(message, group_name=None, host=None):
    group_name = group_name.lower()
    res = group_info(group_name)
    subject = "Group Info -- Success"
    body = "Group info for %s:\n" % (group_name)
    if (res['status']):
        body = "Group Name: %s@%s, Active: %s\n\n" % (res['group_name'], host,
                                                      res['active'])
        for member in res['members']:
            body += "%s : %s\n" % ('Email: ', member['email'])
            body += "%s : %s\n" % ('Active: ', member['active'])
            body += "%s : %s\n" % ('Member: ', member['member'])
            body += "%s : %s\n" % ('Guest: ', member['guest'])
            body += "%s : %s\n" % ('Moderator: ', member['moderator'])
            body += "%s : %s\n" % ('Admin: ', member['admin'])
        body += "\n..........................\n"
    else:
        subject = "Group Info -- Error"
        body = "Error Message: %s" % (res['code'])

    mail = MailResponse(From=NO_REPLY,
                        To=message['From'],
                        Subject=subject,
                        Body=body)
    relay.deliver(mail)
Example #9
0
def help(message, address=None, host=None):

    if WEBSITE == 'squadbox':
        # we should change this to actually send a useful help email
        # with the possible via-email commands in squadbox
        return

    elif WEBSITE == 'murmur':
        to_addr = message['From']
        from_addr = address + '@' + HOST
        subject = "Help"
        body = "Welcome to %s. Please find below a general help on managing a group mailing list.\n\n" % (
            host)
        body += "To create a new group: <name>+create@%s\n" % (host)
        body += "To activate/re-activate your group: <name>+activate@%s\n" % (
            host)
        body += "To de-activate your group: <name>+deactivate@%s\n" % (host)
        body += "To subscribe to a group: <name>+subscribe@%s\n" % (host)
        body += "To unsubscribe from a group: <name>+unsubscribe@%s\n" % (host)
        body += "To see details of a group: <name>+info@%s\n" % (host)
        body += "To see a listing of all the groups: all@%s\n" % (host)
        body += "To get help: help@%s\n" % (host)
        body += "To post message to a group: <name>@%s\n\n" % (host)
        body += "Please substitute '<name>' with your group name."
        mail = MailResponse(From=from_addr,
                            To=to_addr,
                            Subject=subject,
                            Body=body)
        relay.deliver(mail)
        return
Example #10
0
def unsubscribe(message, group_name=None, host=None):

    if WEBSITE == 'squadbox':
        logging.debug("No unsubscribing via email in Squadbox")
        return

    elif WEBSITE == 'murmur':
        group = None
        group_name = group_name.lower()
        name, addr = parseaddr(message['from'].lower())

        try:
            user = UserProfile.objects.get(email=addr)

        except UserProfile.DoesNotExist:
            error_msg = 'Your email is not in the %s system. Ask the admin of the group to add you.' % WEBSITE
            send_error_email(group_name, error_msg, addr, ADMIN_EMAILS)
            return

        res = unsubscribe_group(group_name, user)
        subject = "Unsubscribe -- Success"
        body = "You are now unsubscribed from: %s@%s." % (group_name, host)
        body += " To resubscribe, reply to this email."

        if (not res['status']):
            subject = "Unsubscribe -- Error"
            body = "Error Message: %s" % (res['code'])

        mail = MailResponse(From=NO_REPLY,
                            To=message['From'],
                            Subject=subject,
                            Body=body)
        mail['Reply-To'] = '%s+subscribe@%s' % (group_name, host)
        relay.deliver(mail)
Example #11
0
def info(message, group_name=None, host=None):

    # for now I'm not sure what we would have here,
    # but we can change this later on.
    if WEBSITE == 'squadbox':
        logging.debug("No group info sent via email in Squadbox")
        return

    elif WEBSITE == 'murmur':
        group_name = group_name.lower()
        res = group_info(group_name)
        subject = "Group Info -- Success"
        body = "Group info for %s:\n" % (group_name)
        if (res['status']):
            body = "Group Name: %s@%s, Active: %s\n\n" % (res['group_name'],
                                                          host, res['active'])
            for member in res['members']:
                body += "%s : %s\n" % ('Email: ', member['email'])
                body += "%s : %s\n" % ('Active: ', member['active'])
                body += "%s : %s\n" % ('Member: ', member['member'])
                body += "%s : %s\n" % ('Guest: ', member['guest'])
                body += "%s : %s\n" % ('Moderator: ', member['moderator'])
                body += "%s : %s\n" % ('Admin: ', member['admin'])
            body += "\n..........................\n"
        else:
            subject = "Group Info -- Error"
            body = "Error Message: %s" % (res['code'])

        mail = MailResponse(From=NO_REPLY,
                            To=message['From'],
                            Subject=subject,
                            Body=body)
        relay.deliver(mail)
Example #12
0
def handle_unfollow_tag(message,
                        group_name=None,
                        tag_name=None,
                        suffix=None,
                        host=None):

    if WEBSITE == 'squadbox':
        return

    elif WEBSITE == 'murmur':

        _, addr = parseaddr(message['From'].lower())
        res = unfollow_tag(tag_name, group_name, email=addr)

        if (res['status']):
            body = "You unfollowed the tag \"%s\" successfully." % res[
                'tag_name']
        else:
            body = "Error Message: %s" % (res['code'])

        mail = MailResponse(From=NO_REPLY,
                            To=addr,
                            Subject=res['tag_name'],
                            Body=body)
        relay.deliver(mail)
Example #13
0
    def save(self,
             domain_override=None,
             subject_template_name='registration/password_reset_subject.txt',
             email_template_name='registration/password_reset_email.html',
             extra_email_context=None,
             html_email_template_name="",
             use_https=False,
             token_generator=default_token_generator,
             from_email=None,
             request=None,
             *args,
             **kwargs):
        """
        Generates a one-use only link for resetting password and sends to the
        user.
        """
        logger.info("reset form")

        from django.core.mail import send_mail
        UserModel = get_user_model()
        email = self.cleaned_data["email"]
        active_users = UserModel._default_manager.filter(email__iexact=email,
                                                         is_active=True)
        for user in active_users:
            # Make sure that no email is sent to a user that actually has
            # a password marked as unusable
            if not user.has_usable_password():
                continue

            if not domain_override:
                domain = get_current_site(request).domain
            else:
                domain = domain_override

            c = {
                'email': user.email,
                'domain': domain,
                'site_name': WEBSITE.title(),
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'user': user,
                'token': token_generator.make_token(user),
                'protocol': 'https' if use_https else 'http',
            }
            subject = loader.render_to_string(subject_template_name, c)
            # Email subject *must not* contain newlines
            subject = ''.join(subject.splitlines())
            email = loader.render_to_string(email_template_name, c)

            from smtp_handler.utils import relay_mailer
            from lamson.mail import MailResponse
            mail = MailResponse(From=DEFAULT_FROM_EMAIL,
                                To=user.email,
                                Subject=subject,
                                Body=email)
            relay_mailer.deliver(mail, To=user.email)
Example #14
0
 def email_user(self, subject, message, from_email=None):
     """
     Sends an email to this User.
     """
     from smtp_handler.utils import relay_mailer
     from lamson.mail import MailResponse
     mail = MailResponse(From=DEFAULT_FROM_EMAIL,
                         To=self.email,
                         Subject=subject,
                         Body=message)
     relay_mailer.deliver(mail, To=self.email)
Example #15
0
def test_craft_response_no_attachment():
    sample = MailResponse(To=list_name + "@librelist.com",
                          From=user_full_address,
                          Subject="Test message with attachments.",
                          Body="The body as one attachment.")

    im = sample.to_message()
    assert_equal(len([x for x in im.walk()]), 1)
    assert_equal(im.get_payload(), sample.Body)

    inmsg = MailRequest("fakepeer", None, None, str(sample))
    assert_equal(len(inmsg.all_parts()), 0)
    assert_equal(inmsg.body(), sample.Body)

    outmsg = craft_response(inmsg, list_name, list_name + "@librelist.com")

    om = outmsg.to_message()
    assert_equal(om.get_payload(), sample.Body)

    assert_equal(len([x for x in om.walk()]), len([x for x in im.walk()]))
Example #16
0
def upvote(post_id, email=None, user=None):
	res = {'status':False}
	p = None
	try:
		if email:
			user = UserProfile.objects.get(email=email)
			
		#Email the owner of the post when upvoted
		email_addr = email.strip()
		mail = MailResponse(From = 'no-reply@' + BASE_URL, 
							To = email_addr, 
							Subject  = "Your Post Has Been Upvoted")

		#email_user = UserProfile.objects.filter(email=email_addr)
		message = "Your post %s has been upvoted by %s" % (post_id, user)
		
		mail.Html = message
		logging.debug('TO LIST: ' + str(email_addr))
		relay_mailer.deliver(mail, To = [email_addr])

		p = Post.objects.get(id=int(post_id))
		l = Upvote.objects.get(post=p, user=user)
		res['status'] = True
		res['thread_id'] = p.thread.id
		res['post_name'] = p.subject
		res['post_id'] = p.id
		res['group_name'] = p.group.name
	except UserProfile.DoesNotExist:
		res['code'] = msg_code['USER_DOES_NOT_EXIST'] % email
	except Upvote.DoesNotExist:
		l = Upvote(post=p, user=user)
		l.save()
		res['status'] = True
		res['thread_id'] = p.thread.id
		res['post_name'] = p.subject
		res['post_id'] = p.id
		res['group_name'] = p.group.name
	except:
		res['code'] = msg_code['UNKNOWN_ERROR']
	logging.debug(res)
	return res
Example #17
0
def upvote(post_id, email=None, user=None):
    res = {'status': False}
    p = None
    try:
        if email:
            user = UserProfile.objects.get(email=email)

        #Email the owner of the post when upvoted
        email_addr = email.strip()
        mail = MailResponse(From='no-reply@' + BASE_URL,
                            To=email_addr,
                            Subject="Your Post Has Been Upvoted")

        #email_user = UserProfile.objects.filter(email=email_addr)
        message = "Your post %s has been upvoted by %s" % (post_id, user)

        mail.Html = message
        logging.debug('TO LIST: ' + str(email_addr))
        relay_mailer.deliver(mail, To=[email_addr])

        p = Post.objects.get(id=int(post_id))
        l = Upvote.objects.get(post=p, user=user)
        res['status'] = True
        res['thread_id'] = p.thread.id
        res['post_name'] = p.subject
        res['post_id'] = p.id
        res['group_name'] = p.group.name
    except UserProfile.DoesNotExist:
        res['code'] = msg_code['USER_DOES_NOT_EXIST'] % email
    except Upvote.DoesNotExist:
        l = Upvote(post=p, user=user)
        l.save()
        res['status'] = True
        res['thread_id'] = p.thread.id
        res['post_name'] = p.subject
        res['post_id'] = p.id
        res['group_name'] = p.group.name
    except:
        res['code'] = msg_code['UNKNOWN_ERROR']
    logging.debug(res)
    return res
Example #18
0
    def get_response(self):
        """
        Creates a Lamson MailResponse instance
        """

        response = MailResponse(Subject=self.subject, 
                                To=self.recipients,
                                From=self.sender,
                                Body=self.body,
                                Html=self.html)

        if self.bcc:
            response.base['Bcc'] = self.bcc

        if self.cc:
            response.base['Cc'] = self.cc

        for attachment in self.attachments:

            response.attach(attachment.filename, 
                            attachment.content_type, 
                            attachment.data, 
                            attachment.disposition)

        return response
Example #19
0
def test_post_message():
    for i in range(0, 3):
        add_subscriber(user_full_address, list_name)

    sample = MailResponse(To=list_name + "@librelist.com",
                          From=user_full_address,
                          Subject="Test post message.",
                          Body="I am telling you guys you are wrong.")

    sample['Message-Id'] = '12313123123123123'

    msg = MailRequest("fakepeer", sample['from'], sample['to'], str(sample))
    post_message(relay(port=8825), msg, list_name, "librelist.com")
Example #20
0
def test_craft_response_no_attachment():
    sample = MailResponse(To=list_name + "@librelist.com",
                          From=user_full_address,
                          Subject="Test message with attachments.",
                          Body="The body as one attachment.")

    im = sample.to_message()
    assert_equal(len([x for x in im.walk()]), 1)
    assert_equal(im.get_payload(), sample.Body)
    
    inmsg = MailRequest("fakepeer", None, None, str(sample))
    assert_equal(len(inmsg.all_parts()), 0)
    assert_equal(inmsg.body(), sample.Body)

    outmsg = craft_response(inmsg, list_name, list_name +
                                        "@librelist.com")
  
    om = outmsg.to_message()
    assert_equal(om.get_payload(), sample.Body)

    assert_equal(len([x for x in om.walk()]),
                 len([x for x in im.walk()]))
Example #21
0
def handle_unfollow(message,
                    group_name=None,
                    thread_id=None,
                    msg_id=None,
                    suffix=None,
                    host=None):
    name, addr = parseaddr(message['From'].lower())
    msg_id = msg_id.lower()
    res = unfollow_thread(thread_id, addr)
    if (res['status']):
        mail = MailResponse(From=NO_REPLY,
                            To=addr,
                            Subject="Success",
                            Body="Unfollow success")
        relay.deliver(mail)
    else:
        mail = MailResponse(From=NO_REPLY,
                            To=addr,
                            Subject="Error",
                            Body="Error Message: %s" % (res['code']))
        relay.deliver(mail)
    return
Example #22
0
def test_archive_enqueue():
    msg = MailResponse(From=u'"p\xf6stal Zed" <*****@*****.**>',
                       To="*****@*****.**",
                       Subject="test message",
                       Body="This is a test.")

    archive.enqueue('test.list', msg)
    archived = delivered('zedshaw', to_queue=queue(queue_path))
    assert archived, "Didn't get archived."
    as_string = str(archived)

    assert '-AT-' in str(archived), "Didn't get obfuscated"
    assert '<' in as_string and '"' in as_string and '>' in as_string, "Unicode email screwed up."
Example #23
0
def create(message, group_name=None, host=None):
    group_name = group_name.lower()
    name, addr = parseaddr(message['from'].lower())
    res = create_group(group_name, addr)
    subject = "Create Group -- Success"
    body = "Mailing group %s@%s created" % (group_name, host)
    if (not res['status']):
        subject = "Create Group -- Error"
        body = "Error Message: %s" % (res['code'])
    mail = MailResponse(From=NO_REPLY,
                        To=message['From'],
                        Subject=subject,
                        Body=body)
    relay.deliver(mail)
Example #24
0
def send_account_info(message, address=None, host=None):
    if str(message['From']) == "*****@*****.**" and (
            "Account activation on Murmur" in str(message['Subject'])
            or "Password reset on Murmur" in str(message['Subject'])):
        logging.debug(message['Subject'])
        logging.debug(message['To'])
        logging.debug(message['From'])

        email_message = email.message_from_string(str(message))
        msg_text = get_body(email_message)
        mail = MailResponse(From=NO_REPLY,
                            To=message['To'],
                            Subject=message['Subject'],
                            Body=msg_text['plain'])
        relay.deliver(mail)
Example #25
0
def subscribe(message, group_name=None, host=None):
    group = None
    group_name = group_name.lower()
    name, addr = parseaddr(message['from'].lower())
    res = subscribe_group(group_name, addr)
    subject = "Subscribe -- Success"
    body = "You are now subscribed to: %s@%s" % (group_name, host)
    if (not res['status']):
        subject = "Subscribe -- Error"
        body = "Error Message: %s" % (res['code'])
    mail = MailResponse(From=NO_REPLY,
                        To=message['From'],
                        Subject=subject,
                        Body=body)
    relay.deliver(mail)
Example #26
0
def all(message, address=None, host=None):
    res = list_groups()
    subject = "Listing Groups -- Success"
    body = "Listing all the groups \n\n"
    if (res['status']):
        for g in res['groups']:
            body = body + "Name: " + g['name'] + "\t\tActive:" + str(
                g['active']) + "\n"
    else:
        subject = "Listing Groups -- Error"
        body = "Error Message: %s" % (res['code'])
    mail = MailResponse(From=NO_REPLY,
                        To=message['From'],
                        Subject=subject,
                        Body=body)
    relay.deliver(mail)
Example #27
0
def craft_response(message, list_name, list_addr):
    response = MailResponse(To=list_addr,
                            From=message['from'],
                            Subject=message['subject'])

    msg_id = message['message-id']

    response.update({
        "Sender":
        list_addr,
        "Reply-To":
        list_addr,
        "List-Id":
        list_addr,
        "List-Unsubscribe":
        "<mailto:%[email protected]>" % list_name,
        "List-Archive":
        "<http://librelist.com/archives/%s/>" % list_name,
        "List-Post":
        "<mailto:%s>" % list_addr,
        "List-Help":
        "<http://librelist.com/help.html>",
        "List-Subscribe":
        "<mailto:%[email protected]>" % list_name,
        "Return-Path":
        list_addr,
        "Precedence":
        'list',
    })

    if 'date' in message:
        response['Date'] = message['date']

    if 'references' in message:
        response['References'] = message['References']
    elif msg_id:
        response['References'] = msg_id

    if msg_id:
        response['message-id'] = msg_id

        if 'in-reply-to' not in message:
            response["In-Reply-To"] = message['Message-Id']

    if message.all_parts():
        response.attach_all_parts(message)
    else:
        response.Body = message.body()

    return response
Example #28
0
def handle_follow_tag(message, group_name=None, tag_name=None, suffix=None, host=None):

    if WEBSITE == 'squadbox':
        return

    elif WEBSITE == 'murmur':
        _, addr = parseaddr(message['From'].lower())
        res = follow_tag(tag_name, group_name, email=addr)

        if(res['status']):
            body = "Success! You are now following the tag \"%s\". You will receive emails for all following emails with this tag." % res['tag_name']
        else:
            body = "Sorry there was an error: %s" % (res['code'])

        mail = MailResponse(From = NO_REPLY, To = addr, Subject = res['tag_name'], Body = body)
        relay.deliver(mail)
Example #29
0
def handle_unmute(message, group_name=None, thread_id=None, suffix=None, host=None):

    if WEBSITE == 'squadbox':
        return

    elif WEBSITE == 'murmur':
        _, addr = parseaddr(message['From'].lower())
        res = unmute_thread(thread_id, email=addr)

        if(res['status']):
            body = "You unmuted the thread \"%s\" successfully. You will receive emails for all following replies to this thread." % res['thread_name']
        else:
            body = "Error Message: %s" %(res['code'])

        mail = MailResponse(From = NO_REPLY, To = addr, Subject = res['thread_name'], Body = body)
        relay.deliver(mail)
Example #30
0
def handle_mute_tag(message, group_name=None, tag_name=None, suffix=None, host=None):

    if WEBSITE == 'squadbox':
        return

    elif WEBSITE == 'murmur':

        _, addr = parseaddr(message['From'].lower())
        res = mute_tag(tag_name, group_name, email=addr)
        if(res['status']):
            body = "Success! You have now muted the tag \"%s\"." % res['tag_name']
        else:
            body = "Sorry there was an error: %s" % (res['code'])

        mail = MailResponse(From = NO_REPLY, To = addr, Subject = res['tag_name'], Body = body)
        relay.deliver(mail)
Example #31
0
def send_account_info(message, address=None, host=None):

    subj_string = message['Subject'].encode('utf-8').lower()
    activation_str = ("account activation on %s" % WEBSITE).lower()
    reset_str = ("password reset on %s" % WEBSITE).lower()

    logging.debug(message['Subject'])
    logging.debug(message['To'])
    logging.debug(message['From'])

    if message['From'].encode('utf-8') == NO_REPLY and (activation_str in subj_string or reset_str in subj_string):

        email_message = email.message_from_string(str(message))
        msg_text = get_body(email_message)
        mail = MailResponse(From = NO_REPLY, To = message['To'], Subject = message['Subject'], Body = msg_text['plain'])
        relay.deliver(mail)
Example #32
0
def deactivate(message, group_name=None, host=None):

    if WEBSITE == 'squadbox':
        logging.debug("Ignoring deactivation message in squadbox")
        return

    group = None
    group_name = group_name.lower()
    name, addr = parseaddr(message['from'].lower())
    res = deactivate_group(group_name, addr)
    subject = "De-activate Group -- Success"
    body = "De-activated: %s@%s" %(group_name, host)
    if(not res['status']):
        subject = "De-activate Group -- Error"
        body = "Error Message: %s" %(res['code'])
    mail = MailResponse(From = NO_REPLY, To = message['From'], Subject = subject, Body = body)
    relay.deliver(mail)
Example #33
0
def create(message, group_name=None, host=None):
    # at least for now, for now we don't need this
    if WEBSITE == 'squadbox':
        logging.debug("Ignored message to create group via email, not used in Squadbox")
        return

    elif WEBSITE == 'murmur':
        group_name = group_name.lower()
        name, addr = parseaddr(message['from'].lower())
        res = create_group(group_name, addr)
        subject = "Create Group -- Success"
        body = "Mailing group %s@%s created" %(group_name, host)
        if(not res['status']):
            subject = "Create Group -- Error"
            body = "Error Message: %s" %(res['code'])
        mail = MailResponse(From = NO_REPLY, To = message['From'], Subject = subject, Body = body)
        relay.deliver(mail)
Example #34
0
def handle_post(message, address=None, host=None):

    # restart the db connection
    django.db.close_connection()

    if '+' in address and '__' in address:
        return

    address = cleanAddress(address)

    reserved = filter(lambda x: address.endswith(x), RESERVED)
    if (reserved):
        return

    _, sender_addr = parseaddr(message['From'])
    sender_addr = sender_addr.lower()
    _, to_addr = parseaddr(message['To'])
    to_addr = to_addr.lower()

    verified = isSenderVerified(message)

    group_name = address
    try:
        group = Group.objects.get(name=group_name)
    except Group.DoesNotExist:
        msg = '%s with name %s does not exist.' % (GROUP_OR_SQUAD[WEBSITE],
                                                   group_name)
        send_error_email(group_name, msg, sender_addr, ADMIN_EMAILS)
        return

    # deal with Gmail forwarding verification emails:
    if sender_addr == "*****@*****.**":
        email_message = email.message_from_string(str(message))
        msg_text = get_body(email_message)['plain']
        forward_to = msg_text.split(' ', 1)[0]
        content = "The message below is forwarded to you from Gmail - to complete the setup of your Gmail integration, please click the confirmation link below.\n\n"
        mail = MailResponse(
            From=NO_REPLY,
            To=forward_to,
            Subject=(WEBSITE +
                     " setup: please click the confirmation link inside"),
            Body=content + msg_text)
        relay.deliver(mail)
        return

    handler_funcs[WEBSITE](message, group, host, verified)
Example #35
0
def handle_upvote(message,
                  group_name=None,
                  post_id=None,
                  suffix=None,
                  host=None):
    name, addr = parseaddr(message['from'].lower())
    res = upvote(post_id, email=addr, user=None)
    if (res['status']):
        subject = 'Success'
        body = "Upvoted the post: %s" % (post_id)

    else:
        subject = 'Error'
        body = "Invalid post: %s" % (post_id)

    mail = MailResponse(From=NO_REPLY, To=addr, Subject=subject, Body=body)
    relay.deliver(mail)
Example #36
0
def subscribe(message, group_name=None, host=None):

    # people will never be able to subscribe to a squadbox
    # group themselves; they must be added by the admin.
    if WEBSITE == 'squadbox':
        logging.debug("No subscribing via email in Squadbox")
        return

    elif WEBSITE == 'murmur':
        group = None
        group_name = group_name.lower()
        name, addr = parseaddr(message['from'].lower())

        try:
            user = UserProfile.objects.get(email=addr)
            group = Group.objects.get(name=group_name)

        except UserProfile.DoesNotExist:
            error_msg = 'Your email is not in the %s system. Ask the admin of the group to add you.' % WEBSITE
            send_error_email(group_name, error_msg, addr, ADMIN_EMAILS)
            return

        except Group.DoesNotExist:
            error_msg = 'The group' + group_name + 'does not exist.'
            send_error_email(group_name, error_msg, addr, ADMIN_EMAILS)
            return

        if not group.public:
            error_msg = 'The group ' + group_name + ' is private. Ask the admin of the group to add you.'
            send_error_email(group_name, error_msg, addr, ADMIN_EMAILS)
            return

        res = subscribe_group(group_name, user)
        subject = "Subscribe -- Success"
        body = "You are now subscribed to: %s@%s" % (group_name, host)

        if (not res['status']):
            subject = "Subscribe -- Error"
            body = "Error Message: %s" % (res['code'])

        mail = MailResponse(From=NO_REPLY,
                            To=message['From'],
                            Subject=subject,
                            Body=body)
        relay.deliver(mail)
Example #37
0
def handle_unmute_tag(message,
                      group_name=None,
                      tag_name=None,
                      suffix=None,
                      host=None):
    _, addr = parseaddr(message['From'].lower())
    res = unmute_tag(tag_name, group_name, email=addr)
    if (res['status']):
        body = "You unmuted the tag \"%s\" successfully. You will receive emails for all emails to this tag." % res[
            'tag_name']
    else:
        body = "Error Message: %s" % (res['code'])

    mail = MailResponse(From=NO_REPLY,
                        To=addr,
                        Subject=res['tag_name'],
                        Body=body)
    relay.deliver(mail)
Example #38
0
def craft_response(message, list_name, list_addr):
    response = MailResponse(To=list_addr, 
                            From=message['from'],
                            Subject=message['subject'])

    msg_id = message['message-id']

    response.update({
        "Sender": list_addr, 
        "Reply-To": list_addr,
        "List-Id": list_addr,
        "List-Unsubscribe": "<mailto:%[email protected]>" % list_name,
        "List-Archive": "<http://postosaurus.com/archives/%s/>" % list_name,
        "List-Post": "<mailto:%s>" % list_addr,
        "List-Help": "<http://postosaurus.com/help.html>",
        "List-Subscribe": "<mailto:%[email protected]>" % list_name,
        "Return-Path": list_addr, 
        "Precedence": 'list',
    })

    if 'date' in message:
        response['Date'] = message['date']

    if 'references' in message:
        response['References'] = message['References']
    elif msg_id:
        response['References'] = msg_id

    if msg_id:
        response['message-id'] = msg_id

        if 'in-reply-to' not in message:
            response["In-Reply-To"] = message['Message-Id']

    if message.all_parts():
        for part in message.all_parts():
            if part:
                response.attach_part(part)

        response.base.content_encoding = message.base.content_encoding.copy()
    else:
        response.Body = message.body()

    return response
Example #39
0
def REMAIL(message, to=None, suffix=None, host=None):
    subject = (message['Subject'] or "").strip().lower()
    body = message.body().strip()
    
    messageId = str(uuid.uuid1())
    utils.mail_to_file(message, filename=messageId)
    
    if subject == 'remailer-stats':
        logging.debug("Processing a remailer-stats request..." + messageId)
        stats = "This is not implemented yet."
        if simplifyEmail(message['from']).lower() in getRemailerConfig('blockedaddresses'):
            logging.debug("Skipping the remailer-stats request because sender is in the blocked addresses..." + messageId)
        else:
            mail = MailResponse(To = simplifyEmail(message['from']),
                                From = getRemailerConfig('remailernobodyaddress'),
                                Subject = "Statistics for the " + getRemailerConfig('remailershortname') + " remailer",
                                Body = stats)
            relay.deliver(mail.to_message())
    elif subject == 'remailer-conf':
        logging.debug("Processing a remailer-conf request..." + messageId)
        conf = "This is not implemented yet."
        if simplifyEmail(message['from']).lower() in getRemailerConfig('blockedaddresses'):
            logging.debug("Skipping the remailer-conf request because sender is in the blocked addresses..." + messageId)
        else:
            mail = MailResponse(To = simplifyEmail(message['from']),
                                From = getRemailerConfig('remailernobodyaddress'),
                                Subject = "Capabilities of the " + getRemailerConfig('remailershortname') + " remailer",
                                Body = conf)
            relay.deliver(mail.to_message())
    elif subject == 'remailer-adminkey':
        logging.debug("Processing a remailer-adminkey request..." + messageId)
        if simplifyEmail(message['from']).lower() in getRemailerConfig('blockedaddresses'):
            logging.debug("Skipping the remailer-adminkey request because sender is in the blocked addresses..." + messageId)
        else:
            adminkey = view.respond(
                    getRemailerConfig(), 
                    'adminkey.msg',
                    From=getRemailerConfig('remailernobodyaddress'),
                    To=simplifyEmail(message['from']),
                    Subject='Admin Contact Key')
            relay.deliver(adminkey)
    elif subject == 'remailer-help':
        logging.debug("Processing a remailer-help request..." + messageId)
        if simplifyEmail(message['from']).lower() in getRemailerConfig('blockedaddresses'):
            logging.debug("Skipping the remailer-help request because sender is in the blocked addresses..." + messageId)
        else:
            help = view.respond(
                    getRemailerConfig({'senderaddress' : simplifyEmail(message['from'])}), 
                    'help.msg',
                    From=getRemailerConfig('remailernobodyaddress'),
                    To=simplifyEmail(message['from']),
                    Subject='Remailer Help')
            relay.deliver(help)
    elif subject == 'remailer-key' or subject == 'remailer-keys':
        logging.debug("Processing a remailer-key request..." + messageId)
        if simplifyEmail(message['from']).lower() in getRemailerConfig('blockedaddresses'):
            logging.debug("Skipping the remailer-key request because sender is in the blocked addresses..." + messageId)
        else:
            privkeys = getKeyStore().listPrivateKeys()
            if len(privkeys) > 1:
                raise Exception("More than one private key found in the keystore...")
            mixKey = getKeyStore().getPublicKey(privkeys[0]).toMixFormat()
            
            mixKey = getRemailerConfig().getMixKeyHeader(privkeys[0]) + "\n\n" + mixKey
            
            keys = ""
            keys += getRemailerConfig().getCapString()
            keys += "\n\n"
            keys += mixKey
            
            mail = MailResponse(To = simplifyEmail(message['from']),
                                From = getRemailerConfig('remailernobodyaddress'),
                                Subject = "Remailer key for " + getRemailerConfig('remailershortname'),
                                Body = keys)
            relay.deliver(mail.to_message())
    else:
        logging.debug("Processing a Message..." + messageId)
        body = body.strip()

        if body.startswith('destination-block'):
            logging.debug("Processing a destination-block message..." + messageId)
            
            bodylines = body.split("\n")
            blockaddress = bodylines[0].replace("destination-block ", "").lower().strip()
            logging.debug("Processing a destination-block request for " + blockaddress)

            getRemailerConfig('blockedaddresses').append(blockaddress)
            
            f = open(getRemailerConfig('filelocations')['blockedaddresses'], 'a')
            f.write(blockaddress + "\n")
            f.close()
        elif body.startswith('::'):
            logging.debug("Processing a Mix Message..." + messageId)
            mixmsg = MixMessage(body)
            
            #This is where it _should_ go into the pool, but won't for now...
            if mixmsg.PacketType == MixPacketType.IntermediateHop:
                mail = MailResponse(To = mixmsg.deliveryTo(),
                                    From = getRemailerConfig('remailernobodyaddress'),
                                    Subject = mixmsg.deliverySubject(),
                                    Body = mixmsg.deliveryBody())
                relay.deliver(mail.to_message())
                logging.debug("Delivering an Intermediate Hop Message..." + messageId)
            elif mixmsg.PacketType == MixPacketType.FinalHop:
                for deliveryAddr in mixmsg.deliveryTo():
                    logging.debug("Delivering a Final Hop Message..." + messageId)
                    if deliveryAddr.lower() in getRemailerConfig('blockedaddresses'):
                        logging.debug("Skipping a destination because it is in the blocked addresses..." + messageId)
                    else:
                        mail = MailResponse(To = deliveryAddr,
                                        From = getRemailerConfig('remailernobodyaddress'),
                                        Subject = mixmsg.deliverySubject(),
                                        Body = mixmsg.deliveryBody())
                        for h, v in mixmsg.deliveryHeaders():
                            mail[h] = v
                        relay.deliver(mail.to_message())
            elif mixmsg.PacketType == MixPacketType.DummyMessage:
                logging.debug("Ignoring a Dummy Message...")
            else:  
                logging.debug("Mix Message not understood..." + messageId)
                
        elif body.startswith('-----BEGIN PGP MESSAGE-----'):
            logging.debug("Processing a PGP message..." + messageId)
            pass
        else:
            logging.debug("Passing on a remailer message not understood..." + messageId)
    return REMAIL    
Example #40
0
def REMAIL(message, to=None, suffix=None, host=None):
    subject = (message['Subject'] or "").strip().lower()
    body = message.body().strip()
    
    messageId = str(uuid.uuid1())
    utils.mail_to_file(message, filename=messageId)
    
    if subject == 'remailer-stats':
        logging.debug("Processing a remailer-stats request...")
        pass
    elif subject == 'remailer-help':
        logging.debug("Processing a remailer-help request...")
        help = view.respond(
                getRemailerConfig({'senderaddress' : simplifyEmail(message['from'])}), 
                'help.msg',
                From=getRemailerConfig('remailernobodyaddress'),
                To=message['from'],
                Subject='Remailer Help')
        relay.deliver(help)
        pass
    elif subject == 'remailer-key' or subject == 'remailer-keys':
        logging.debug("Processing a remailer-key request...")
        
        privkeys = getKeyStore().listPrivateKeys()
        if len(privkeys) > 1:
            raise Exception("More than one private key found in the keystore...")
        mixKey = getKeyStore().getPublicKey(privkeys[0]).toMixFormat()
        
        mixKey = getRemailerConfig().getMixKeyHeader(privkeys[0]) + "\n\n" + mixKey
        
        keys = ""
        keys += getRemailerConfig().getCapString()
        keys += "\n\n"
        keys += mixKey
        
        mail = MailResponse(To = simplifyEmail(message['from']),
                            From = getRemailerConfig('remailernobodyaddress'),
                            Subject = "Remailer key for " + getRemailerConfig('remailershortname'),
                            Body = keys)
        relay.deliver(mail.to_message())
    else:
        logging.debug("Processing a Message...")
        body = body.strip()

        if body.startswith('destination-block'):
            logging.debug("Processing a destination-block message...")
            pass
        elif body.startswith('::'):
            logging.debug("Processing a Mix Message...")
            mixmsg = MixMessage(body)
            
            #This is where it _should_ go into the pool, but won't for now...
            if mixmsg.PacketType == MixPacketType.IntermediateHop:
                mail = MailResponse(To = mixmsg.deliveryTo(),
                                    From = getRemailerConfig('remailernobodyaddress'),
                                    Subject = mixmsg.deliverySubject(),
                                    Body = mixmsg.deliveryBody())
                relay.deliver(mail.to_message())
                logging.debug("Delivering an Intermediate Hop Message...")
            elif mixmsg.PacketType == MixPacketType.FinalHop:
                for deliveryAddr in mixmsg.deliveryTo():
                    mail = MailResponse(To = deliveryAddr,
                                    From = getRemailerConfig('remailernobodyaddress'),
                                    Subject = mixmsg.deliverySubject(),
                                    Body = mixmsg.deliveryBody())
                    for h, v in mixmsg.deliveryHeaders():
                        mail[h] = v
                    relay.deliver(mail.to_message())
                    logging.debug("Delivering a Final Hop Message...")
            elif mixmsg.PacketType == MixPacketType.DummyMessage:
                logging.debug("Ignoring a Dummy Message...")
            else:  
                logging.debug("Mix Message not understood...", messageId)
                
        elif body.startswith('-----BEGIN PGP MESSAGE-----'):
            logging.debug("Processing a PGP message...")
            pass
        else:
            logging.debug("Passing on a remailer message not understood...")
    return REMAIL