Пример #1
0
    def test_craft_from_sample(self):
        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/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."
Пример #2
0
    def test_mail_response_mailing_list_headers(self):
        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], "%s: %r != %r" % (
                header, msg[header], req[header])

        # try a delete
        del msg['Precedence']
Пример #3
0
def test_mail_response_attachments():
    sample = mail.MailResponse(To="receiver@localhost", 
                                 Subject="Test message",
                                 From="sender@localhost",
                                 Body="Test from test_mail_response_attachments.")
    readme_data = open("./README.md").read()

    assert_raises(AssertionError, sample.attach, filename="./README.md", disposition="inline")

    sample.attach(filename="./README.md", content_type="text/plain", disposition="inline")
    assert len(sample.attachments) == 1
    assert sample.multipart

    msg = sample.to_message()
    assert_equal(len(msg.get_payload()), 2)

    sample.clear()
    assert len(sample.attachments) == 0
    assert not sample.multipart

    sample.attach(data=readme_data, filename="./README.md", content_type="text/plain")

    msg = sample.to_message()
    assert_equal(len(msg.get_payload()), 2)
    sample.clear()

    sample.attach(data=readme_data, content_type="text/plain")
    msg = sample.to_message()
    assert_equal(len(msg.get_payload()), 2)

    return sample
Пример #4
0
def craft_response(message, From, To, contact_addr=None):
    response = mail.MailResponse(To=To, From=From, Subject=message['subject'])

    msg_id = message['message-id']

    if contact_addr:
        response.update({
            "Sender": contact_addr,
            "Reply-To": contact_addr,
            "Return-Path": contact_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
Пример #5
0
 def send(self, To, From, Subject, Body):
     """
     Does what it says, sends an email.  If you need something more complex
     then look at salmon.mail.MailResponse.
     """
     msg = mail.MailResponse(To=To, From=From, Subject=Subject, Body=Body)
     self.deliver(msg)
Пример #6
0
def test_mail_response_html_and_plain_text():
    sample = mail.MailResponse(To="receiver@localhost", 
                                 Subject="Test message",
                                 From="sender@localhost",
                                 Html="<html><body><p>Hi there.</p></body></html>",
                                 Body="Test from test_mail_response_html_and_plain_text.")
    return sample
Пример #7
0
def test_sendmail_command():
    sys.stdin.read.function()

    msg = mail.MailResponse(To="tests@localhost", From="tests@localhost",
                            Subject="Hello", Body="Test body.")
    sys.stdin.read.return_value = str(msg)
    commands.sendmail_command(port=8899)
Пример #8
0
    def command(port,
                host,
                username=None,
                password=None,
                ssl=None,
                starttls=None,
                lmtp=None,
                sender=None,
                to=None,
                subject=None,
                body=None,
                attach=None):
        message = mail.MailResponse(From=sender,
                                    To=to,
                                    Subject=subject,
                                    Body=body)
        if attach:
            message.attach(attach)

        relay = server.Relay(host,
                             port=port,
                             username=username,
                             password=password,
                             ssl=ssl,
                             starttls=starttls,
                             lmtp=lmtp,
                             debug=False)
        relay.deliver(message)
Пример #9
0
    def respond(self, variables, content, **kwd):
        """
        Works like salmon.view.respond letting you craft a
        salmon.mail.MailResponse immediately from the results of
        a salmon.html.HtmlMail.render call.  Simply pass in the
        From, To, and Subject parameters you would normally pass
        in for MailResponse, and it'll craft the HTML mail for
        you and return it ready to deliver.

        A slight convenience in this function is that if the
        Body kw parameter equals the content parameter, then
        it's assumed you want the raw markdown content to be
        sent as the text version, and it will produce a nice
        dual HTML/text email.
        """
        assert content, "You must give a contents template."

        if kwd.get('Body', None) == content:
            kwd['Body'] = view.render(variables, content)

        for key in kwd:
            kwd[key] = kwd[key] % variables
        
        msg = mail.MailResponse(**kwd)
        msg.Html = self.render(variables, content)

        return msg
Пример #10
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')
Пример #11
0
def send(port,
         host,
         username=None,
         password=None,
         ssl=None,
         starttls=None,
         lmtp=None,
         sender=None,
         to=None,
         subject=None,
         body=None,
         attach=None):
    """
    Sends an email to someone as a test message.
    See the sendmail command for a sendmail replacement.
    """
    message = mail.MailResponse(From=sender, To=to, Subject=subject, Body=body)
    if attach:
        message.attach(attach)

    relay = server.Relay(host,
                         port=port,
                         username=username,
                         password=password,
                         ssl=ssl,
                         starttls=starttls,
                         lmtp=lmtp,
                         debug=False)
    relay.deliver(message)
Пример #12
0
 def test_mail_response_empty(self):
     sample = mail.MailResponse(
         To="receiver@localhost",
         Subject="Test message",
         From="sender@localhost",
     )
     assert str(sample)
     return sample
Пример #13
0
    def test_mail_attach_no_data_or_file(self):
        msg = mail.MailResponse(
            To="receiver@localhost",
            Subject="Test message",
            From="sender@localhost",
        )

        with self.assertRaises(TypeError):
            msg.attach()
Пример #14
0
    def test_mail_attach_file_no_exist(self):
        msg = mail.MailResponse(
            To="receiver@localhost",
            Subject="Test message",
            From="sender@localhost",
        )

        with self.assertRaises(TypeError):
            msg.attach(filename="/filethatshouldnotexist")
Пример #15
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)
Пример #16
0
def test_mail_response_html():
    sample = mail.MailResponse(
        To="receiver@localhost",
        Subject="Test message",
        From="sender@localhost",
        Html="<html><body><p>From test_mail_response_html</p></body></html>",
    )

    return sample
Пример #17
0
def test_mail_response_plain_text():
    sample = mail.MailResponse(
        To="receiver@localhost",
        Subject="Test message",
        From="sender@localhost",
        Body="Test from test_mail_response_plain_text.",
    )

    return sample
Пример #18
0
def test_get():
    q = test_push()
    msg = mail.MailResponse(To="test@localhost", From="test@localhost", Subject="Test", Body="Test")

    key = q.push(str(msg))
    assert key, "Didn't get a key for test_get push."

    msg = q.get(key)
    assert msg, "Didn't get a message for key %r" % key
Пример #19
0
def test_remove():
    q = test_push()
    msg = mail.MailResponse(To="test@localhost", From="test@localhost", Subject="Test", Body="Test")

    key = q.push(str(msg))
    assert key, "Didn't get a key for test_get push."
    assert_equal(q.count(), 2)

    q.remove(key)
    assert_equal(q.count(), 1)
Пример #20
0
def test_remove():
    q = test_push()
    msg = mail.MailResponse(To="test@localhost", From="test@localhost", Subject="Test", Body="Test")

    key = q.push(str(msg))
    assert key, "Didn't get a key for test_get push."
    assert q.count() == 2, "Wrong count %d should be 2" % q.count()

    q.remove(key)
    assert q.count() == 1, "Wrong count %d should be 1" % q.count()
Пример #21
0
def test_sendmail_command():
    sys.stdin.read.function()

    msg = mail.MailResponse(To="tests@localhost",
                            From="tests@localhost",
                            Subject="Hello",
                            Body="Test body.")
    sys.stdin.read.return_value = str(msg)

    command = get_command("sendmail")
    command("--host", "127.0.0.1", "--port", "8899", "test@localhost")
Пример #22
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()]))
Пример #23
0
def test_sendmail_command():
    sys.stdin.read.function()

    msg = mail.MailResponse(To="tests@localhost",
                            From="tests@localhost",
                            Subject="Hello",
                            Body="Test body.")
    sys.stdin.read.return_value = str(msg)

    command = get_command(commands.sendmail_command)
    command(host="127.0.0.1", port=8899, recipients=["test@localhost"])
Пример #24
0
    def test_copy_parts(self):
        with open("tests/data/bounce.msg") as file_obj:
            bm = mail.MailRequest(None, None, None, file_obj.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()

        self.assertEqual(len([x for x in bm.walk()]), len([x for x in resp.walk()]))
Пример #25
0
def test_push():
    q = queue.Queue("run/queue", safe=USE_SAFE)
    q.clear()

    # the queue doesn't really care if its a request or response, as long
    # as the object answers to str(msg)
    msg = mail.MailResponse(To="test@localhost", From="test@localhost", Subject="Test", Body="Test")
    key = q.push(msg)

    assert key, "Didn't get a key for test_get push."

    return q
Пример #26
0
    def test_sendmail_command(self, client_mock):
        sys.stdin.read.function()

        msg = mail.MailResponse(To="tests@localhost",
                                From="tests@localhost",
                                Subject="Hello",
                                Body="Test body.")
        sys.stdin.read.return_value = str(msg)

        runner = CliRunner()
        runner.invoke(commands.main, ("sendmail", "--host", "127.0.0.1",
                                      "--port", "8899", "test@localhost"))
        self.assertEqual(client_mock.return_value.sendmail.call_count, 1)
Пример #27
0
 def test_no_connection(self):
     q = queue.Queue("run/queue")
     msg = mail.MailResponse(To="tests@localhost",
                             From="tests@localhost",
                             Subject="Hello",
                             Body="Test body.")
     q.push(msg)
     runner = CliRunner()
     result = runner.invoke(
         commands.main,
         ("blast", "--host", "127.0.1.2", "--port", "8901", "run/queue"))
     self.assertEqual(result.exit_code, 1)
     self.assertEqual(result.output,
                      "Error: [Errno 111] Connection refused\n")
Пример #28
0
 def test_cleanse_command(self):
     q = queue.Queue("run/queue")
     msg_count = 3
     for i in range(msg_count):
         msg = mail.MailResponse(To="tests%s@localhost" % i,
                                 From="tests%s@localhost" % i,
                                 Subject="Hello",
                                 Body="Test body.")
         q.push(msg)
     self.assertEqual(q.count(), msg_count)
     runner = CliRunner()
     result = runner.invoke(commands.main,
                            ("cleanse", "run/queue", "run/cleansed"))
     self.assertEqual(result.exit_code, 0)
     self.assertEqual(q.count(), msg_count)
     outbox = mailbox.Maildir("run/cleansed", create=False)
     self.assertEqual(len(outbox), msg_count)
Пример #29
0
def respond(variables, Body=None, Html=None, **kwd):
    """
    Does the grunt work of cooking up a MailResponse that's based
    on a template.  The only difference from the salmon.mail.MailResponse
    class and this (apart from variables passed to a template) are that
    instead of giving actual Body or Html parameters with contents,
    you give the name of a template to render.  The kwd variables are
    the remaining keyword arguments to MailResponse of From/To/Subject.

    For example, to render a template for the body and a .html for the Html
    attachment, and to indicate the From/To/Subject do this::

        msg = view.respond(locals(), Body='template.txt',
                          Html='template.html',
                          From='*****@*****.**',
                          To='*****@*****.**',
                          Subject='Test body from "%(person)s".')

    In this case you're using locals() to gather the variables needed for
    the 'template.txt' and 'template.html' templates.  Each template is
    setup to be a text/plain or text/html attachment.  The From/To/Subject
    are setup as needed.  Finally, the locals() are also available as
    simple Python keyword templates in the From/To/Subject so you can pass
    in variables to modify those when needed (as in the %(person)s in Subject).
    """

    if Body is None and Html is None:
        raise TypeError(
            "You need to give either the Body or Html template of the mail.")

    for key in kwd:
        kwd[key] = kwd[key] % variables

    msg = mail.MailResponse(**kwd)

    if Body:
        msg.Body = render(variables, Body)

    if Html:
        msg.Html = render(variables, Html)

    return msg
Пример #30
0
    def test_mail_response_attachments(self):
        sample = mail.MailResponse(
            To="receiver@localhost",
            Subject="Test message",
            From="sender@localhost",
            Body="Test from test_mail_response_attachments.",
        )
        with open("./README.rst") as file_obj:
            readme_data = file_obj.read()

        with self.assertRaises(ValueError):
            sample.attach(data=readme_data, disposition="inline")

        sample.attach(filename="./README.rst",
                      content_type="text/plain",
                      disposition="inline")
        self.assertEqual(len(sample.attachments), 1)
        assert sample.multipart

        msg = sample.to_message()
        self.assertEqual(len(msg.get_payload()), 2)

        sample.clear()
        self.assertEqual(len(sample.attachments), 0)
        assert not sample.multipart

        sample.attach(data=readme_data,
                      filename="./README.rst",
                      content_type="text/plain")

        msg = sample.to_message()
        self.assertEqual(len(msg.get_payload()), 2)
        sample.clear()

        sample.attach(data=readme_data, content_type="text/plain")
        msg = sample.to_message()
        self.assertEqual(len(msg.get_payload()), 2)

        assert str(sample)
        return sample