def test_mail_request():
    # try with a half-assed message
    msg = mail.MailRequest("localhost", "zedfrom@localhost", "zedto@localhost",
                           "Fake body.")
    assert msg['to'] == "zedto@localhost", "To is %r" % msg['to']
    assert msg['from'] == "zedfrom@localhost", "From is %r" % msg['from']

    msg = mail.MailRequest("localhost", "somedude@localhost",
                           ["somedude@localhost"], sample_message)
    assert msg.original == sample_message

    assert_equal(msg['From'], "somedude@localhost")

    assert ("From" in msg)
    del msg["From"]
    assert ("From" not in msg)

    msg["From"] = "nobody@localhost"
    assert ("From" in msg)
    assert_equal(msg["From"], "nobody@localhost")

    # validate that upper and lower case work for headers
    assert ("FroM" in msg)
    assert ("from" in msg)
    assert ("From" in msg)
    assert_equal(msg['From'], msg['fRom'])
    assert_equal(msg['From'], msg['from'])
    assert_equal(msg['from'], msg['fRom'])

    # make sure repr runs
    print repr(msg)

    return msg
Esempio n. 2
0
def test_HtmlMail_content_type_respected():
    generator = html.HtmlMail("style.css", "html_test.html", {})

    resp = generator.respond({},
                             "content.markdown",
                             From="somedude@localhost",
                             To="somedude@localhost",
                             Subject="Test of an HTML mail.",
                             Body="content.markdown")

    req = mail.MailRequest('fakepeer', None, None, str(resp))

    assert_equal(req.base.content_encoding['Content-Type'][0],
                 'multipart/alternative')

    resp2 = mail.MailResponse(To=req['to'],
                              From=req['from'],
                              Subject=req['subject'])
    resp2.attach_all_parts(req)

    assert_equal(resp2.base.content_encoding['Content-Type'],
                 resp.base.content_encoding['Content-Type'])

    assert_equal(resp2.base.content_encoding['Content-Type'][0],
                 'multipart/alternative')

    req2 = mail.MailRequest('fakepeer', None, None, str(resp2))

    assert_equal(resp2.base.content_encoding['Content-Type'][0],
                 'multipart/alternative')

    assert_equal(req2.base.content_encoding['Content-Type'][0],
                 'multipart/alternative')
def test_mail_response_mailing_list_headers():
    list_addr = "test.users@localhost"

    msg = mail.MailResponse(From='somedude@localhost',
                            To=list_addr,
                            Subject='subject',
                            Body="Mailing list reply.")

    print repr(msg)

    msg["Sender"] = list_addr
    msg["Reply-To"] = list_addr
    msg["List-Id"] = list_addr
    msg["Return-Path"] = list_addr
    msg["In-Reply-To"] = 'Message-Id-1231123'
    msg["References"] = 'Message-Id-838845854'
    msg["Precedence"] = 'list'

    data = str(msg)

    req = mail.MailRequest('localhost', 'somedude@localhost', list_addr, data)

    headers = [
        'Sender', 'Reply-To', 'List-Id', 'Return-Path', 'In-Reply-To',
        'References', 'Precedence'
    ]
    for header in headers:
        assert msg[header] == req[header]

    # try a delete
    del msg['Precedence']
def test_craft_from_sample():
    list_name = "test.list"
    user_full_address = "tester@localhost"

    sample = mail.MailResponse(To=list_name + "@localhost",
                               From=user_full_address,
                               Subject="Test message with attachments.",
                               Body="The body as one attachment.")
    sample.update({"Test": "update"})

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

    inmsg = mail.MailRequest("fakepeer", None, None, str(sample))
    assert "Test" in sample.keys()

    for part in inmsg.to_message().walk():
        assert part.get_payload(), "inmsg busted."

    outmsg = mail.MailResponse(To=inmsg['from'],
                               From=inmsg['to'],
                               Subject=inmsg['subject'])

    outmsg.attach_all_parts(inmsg)

    result = outmsg.to_message()

    for part in result.walk():
        assert part.get_payload(), "outmsg parts don't have payload."
Esempio n. 5
0
def test_attach_headers():
    msg = mail.MailRequest('test_attach_headers', 'tester@localhost', '*****@*****.**',
                           'Fake body.')

    comment.attach_headers(msg)
    for key in ['X-Post-Name', 'X-Post-User-ID', 'X-Post-Domain']:
        assert key in msg
Esempio n. 6
0
def test_route_reply():
    msg = mail.MailRequest('fakepeer', from_user['from'], from_user['to'],
                           str(from_user))
    reply = filter.route_reply(msg, marketroid_id, host).to_message()

    # make sure the user's address is never in a header
    for k, v in reply.items():
        assert_not_equal(reply[k], user)
Esempio n. 7
0
def test_cleanse_incoming():
    msg = mail.MailRequest('fakepeer', from_marketroid['from'],
                           from_marketroid['to'], str(from_marketroid))

    reply = filter.cleanse_incoming(msg, user_id, host).to_message()
    assert_equal(reply['from'], marketroid)
    assert_equal(reply['to'], user)
    assert_equal(reply['reply-to'], mk_anon_addr)
Esempio n. 8
0
 def deliver(self, To, From, Subject, Body):
     """Overrides TestConversation.deliver to do it internally."""
     sample = mail.MailResponse(From=From,
                                To=To,
                                Subject=Subject,
                                Body=Body)
     msg = mail.MailRequest('localhost', sample['From'], sample['To'],
                            str(sample))
     routing.Router.deliver(msg)
Esempio n. 9
0
def test_bounce_to_decorator():
    import bounce_filtered_mod
    msg = mail.MailRequest(None, None, None, open("tests/bounce.msg").read())

    Router.deliver(msg)
    assert Router.in_state(bounce_filtered_mod.START, msg)
    assert bounce_filtered_mod.HARD_RAN, "Hard bounce state didn't actually run: %r" % msg.route_to

    msg.bounce.primary_status = (4, u'Persistent Transient Failure')
    Router.clear_states()
    Router.deliver(msg)
    assert Router.in_state(bounce_filtered_mod.START, msg)
    assert bounce_filtered_mod.SOFT_RAN, "Soft bounce didn't actually run."

    msg = mail.MailRequest(None, None, None, open("tests/signed.msg").read())
    Router.clear_states()
    Router.deliver(msg)
    assert Router.in_state(bounce_filtered_mod.END,
                           msg), "Regular messages aren't delivering."
def test_route_to_from_works():
    msg = mail.MailRequest("fakepeer", "from@localhost",
                           [u"<to1@localhost>", u"to2@localhost"], "")
    assert '<' not in msg.route_to, msg.route_to

    msg = mail.MailRequest("fakepeer", "from@localhost",
                           [u"to1@localhost", u"to2@localhost"], "")
    assert '<' not in msg.route_to, msg.route_to

    msg = mail.MailRequest("fakepeer", "from@localhost",
                           [u"to1@localhost", u"<to2@localhost>"], "")
    assert '<' not in msg.route_to, msg.route_to

    msg = mail.MailRequest("fakepeer", "from@localhost", [u"to1@localhost"],
                           "")
    assert '<' not in msg.route_to, msg.route_to

    msg = mail.MailRequest("fakepeer", "from@localhost", [u"<to1@localhost>"],
                           "")
    assert '<' not in msg.route_to, msg.route_to
Esempio n. 11
0
def sendmail_command(port=8825, host='127.0.0.1', debug=0, TRAILING=None):
    """
    Used as a testing sendmail replacement for use in programs
    like mutt as an MTA.  It reads the email to send on the stdin
    and then delivers it based on the port and host settings.

    lamson sendmail -port 8825 -host 127.0.0.1 -debug 0 -- [recipients]
    """
    relay = server.Relay(host, port=port, debug=debug)
    data = sys.stdin.read()
    msg = mail.MailRequest(None, TRAILING, None, data)
    relay.deliver(msg)
Esempio n. 12
0
def test_copy_parts():
    bm = mail.MailRequest(None,None,None, open("tests/bounce.msg").read())
    
    resp = mail.MailResponse(To=bm['to'], From=bm['from'],
                             Subject=bm['subject'])

    resp.attach_all_parts(bm)

    resp = resp.to_message()
    bm = bm.to_message()

    assert_equal(len([x for x in bm.walk()]), len([x for x in resp.walk()]))
Esempio n. 13
0
    def process_message(self, Peer, From, To, Data):
        """
        Called by smtpd.SMTPServer when there's a message received.
        """

        try:
            logging.debug("Message received from Peer: %r, From: %r, to To %r." % (Peer, From, To))
            routing.Router.deliver(mail.MailRequest(Peer, From, To, Data))
        except SMTPError, err:
            # looks like they want to return an error, so send it out
            return str(err)
            undeliverable_message(Data, "Handler raised SMTPError on purpose: %s" % err)
Esempio n. 14
0
def test_craft_response():
    # message from marketroid to the user_anon_addr
    msg = mail.MailRequest('fakepeer', from_marketroid['from'],
                           from_marketroid['to'], str(from_marketroid))

    # the mail a user would need to respond to
    resp = filter.craft_response(msg, msg['From'], user,
                                 mk_anon_addr).to_message()

    assert_equal(resp['from'], marketroid)
    assert_equal(resp['to'], user)
    assert_equal(resp['reply-to'], mk_anon_addr)

    msg = mail.MailRequest('fakepeer', from_user['from'], from_user['to'],
                           str(from_user))

    # the mail a marketroid could respond to
    resp = filter.craft_response(msg, user_anon_addr, marketroid).to_message()
    assert_equal(resp['from'], user_anon_addr)
    assert_equal(resp['to'], marketroid)

    # make sure the user's address is never in a header
    for k, v in resp.items():
        assert_not_equal(resp[k], user)
def test_mail_request_attachments():
    sample = test_mail_response_attachments()
    data = str(sample)

    msg = mail.MailRequest("localhost", None, None, data)

    msg_parts = msg.all_parts()
    sample_parts = sample.all_parts()

    readme = open("./README.md").read()

    # BUG: Python's MIME text attachment decoding drops trailing newline chars

    assert msg_parts[0].body == sample_parts[0].body
    # python drops chars at the end, so can't compare equally
    assert readme.startswith(msg_parts[1].body)
    assert msg.body() == sample_parts[0].body

    # test that we get at least one message for messages without attachments
    sample = test_mail_response_plain_text()
    msg = mail.MailRequest("localhost", None, None, str(sample))
    msg_parts = msg.all_parts()
    assert len(msg_parts) == 0, "Length is %d should be 0." % len(msg_parts)
    assert msg.body()
Esempio n. 16
0
 def process_message(self, Peer, From, To, Data, User):
     """
     Called by smtpd.SMTPServer when there's a message received.
     """
     queue.PEER = Peer  # Shiva - Passing Remote socket to variable PEER defined in 'queue.py' module
     queue.USER = User or "none"  # In case of no username, it defaults to "none"
     try:
         logging.debug(
             "Message received from Peer: %r, From: %r, to To %r." %
             (Peer, From, To))
         routing.Router.deliver(mail.MailRequest(Peer, From, To, Data))
     except SMTPError, err:
         # looks like they want to return an error, so send it out
         return str(err)
         undeliverable_message(
             Data, "Handler raised SMTPError on purpose: %s" % err)
Esempio n. 17
0
def test_bounce_getting_original():
    msg = mail.MailRequest(None, None, None, open("tests/bounce.msg").read())
    msg.is_bounce()

    assert msg.bounce.notification
    assert msg.bounce.notification.body

    assert msg.bounce.report

    for part in msg.bounce.report:
        assert [(k, part[k]) for k in part]
        # these are usually empty, but might not be.  they are in our test
        assert not part.body

    assert msg.bounce.original
    assert_equal(msg.bounce.original['to'], msg.bounce.final_recipient)
    assert msg.bounce.original.body
Esempio n. 18
0
    def get(self, key):
        """
        Get the specific message referenced by the key.  The message is NOT
        removed from the queue.
        """
        msg_file = self.mbox.get_file(key)

        if not msg_file: 
            return None

        msg_data = msg_file.read()

        try:
            return mail.MailRequest(self.dir, None, None, msg_data)
        except Exception, exc:
            logging.exception("Failed to decode message: %s" % exc, msg_data)
            return None
Esempio n. 19
0
def test_bounce_analyzer_on_regular():
    bm = mail.MailRequest(None, None, None, open("tests/signed.msg").read())
    assert not bm.is_bounce()
    assert bm.bounce
    assert bm.bounce.score == 0.0
    assert not bm.bounce.probable()
    assert_equal(bm.bounce.primary_status, (None, None))
    assert_equal(bm.bounce.secondary_status, (None, None))
    assert_equal(bm.bounce.combined_status, (None, None))

    assert not bm.bounce.is_hard()
    assert not bm.bounce.is_soft()

    assert_equal(bm.bounce.remote_mta, None)
    assert_equal(bm.bounce.reporting_mta, None)
    assert_equal(bm.bounce.final_recipient, None)
    assert_equal(bm.bounce.diagnostic_codes, [None, None])
    assert_equal(bm.bounce.action, None)
Esempio n. 20
0
def test_ConfirmationEngine_verify():
    confirm = test_ConfirmationEngine_send()

    resp = mail.MailRequest('fakepeer',
                            '"Somedude Smith" <somedude@localhost>',
                            confirm['Reply-To'], 'Fake body')

    target, _, expect_secret = confirm['Reply-To'].split('-')
    expect_secret = expect_secret.split('@')[0]

    found = engine.verify(target, resp['from'], 'invalid_secret')
    assert not found

    pending = engine.verify(target, resp['from'], expect_secret)
    assert pending, "Verify failed: %r not in %r." % (expect_secret,
                                                      storage.confirmations)

    assert_equal(pending['from'], 'somedude@localhost')
    assert_equal(pending['to'], 'testing-subscribe@localhost')
Esempio n. 21
0
def test_ConfirmationEngine_send():
    queue.Queue('run/queue').clear()
    engine.clear()

    list_name = 'testing'
    action = 'subscribing to'
    host = 'localhost'

    message = mail.MailRequest('fakepeer', 'somedude@localhost',
                               'testing-subscribe@localhost', 'Fake body.')

    engine.send(relay(port=8899), 'testing', message, 'confirmation.msg',
                locals())

    confirm = delivered('confirm')
    assert delivered('somedude', to_queue=engine.pending)
    assert confirm

    return confirm
Esempio n. 22
0
def test_bounce_analyzer_on_bounce():
    bm = mail.MailRequest(None, None, None, open("tests/bounce.msg").read())
    assert bm.is_bounce()
    assert bm.bounce
    assert bm.bounce.score == 1.0
    assert bm.bounce.probable()
    assert_equal(bm.bounce.primary_status, (5, u'Permanent Failure'))
    assert_equal(bm.bounce.secondary_status, (1, u'Addressing Status'))
    assert_equal(bm.bounce.combined_status,
                 (11, u'Bad destination mailbox address'))

    assert bm.bounce.is_hard()
    assert_equal(bm.bounce.is_hard(), not bm.bounce.is_soft())

    assert_equal(bm.bounce.remote_mta, u'gmail-smtp-in.l.google.com')
    assert_equal(bm.bounce.reporting_mta, u'mail.zedshaw.com')
    assert_equal(
        bm.bounce.final_recipient,
        u'*****@*****.**')
    assert_equal(bm.bounce.diagnostic_codes[0], u'550-5.1.1')
    assert_equal(bm.bounce.action, 'failed')
    assert 'Content-Description-Parts' in bm.bounce.headers

    assert bm.bounce.error_for_humans()
def test_msg_is_deprecated():
    warnings.simplefilter("ignore")
    msg = mail.MailRequest(None, None, None, "")
    assert_equal(msg.msg, msg.base)
    resp = mail.MailResponse()
    assert_equal(resp.msg, resp.base)
def test_walk():
    bm = mail.MailRequest(None, None, None, open("tests/bounce.msg").read())
    parts = [x for x in bm.walk()]

    assert parts
    assert_equal(len(parts), 6)
Esempio n. 25
0
def test_bounce_no_headers_error_message():
    msg = mail.MailRequest(None, None, None, "Nothing")
    msg.is_bounce()
    assert_equal(msg.bounce.error_for_humans(),
                 'No status codes found in bounce message.')