Example #1
0
 def test_from_header(self):
     """
     Make sure we can manually set the From header (#9214)
     """
     email = EmailMessage('Subject', 'Content', '*****@*****.**', ['*****@*****.**'], headers={'From': '*****@*****.**'})
     message = email.message()
     self.assertEqual(message['From'], '*****@*****.**')
Example #2
0
 def test_space_continuation(self):
     """
     Test for space continuation character in long (ascii) subject headers (#7747)
     """
     email = EmailMessage('Long subject lines that get wrapped should use a space continuation character to get expected behavior in Outlook and Thunderbird', 'Content', '*****@*****.**', ['*****@*****.**'])
     message = email.message()
     self.assertEqual(message['Subject'], 'Long subject lines that get wrapped should use a space continuation\n character to get expected behavior in Outlook and Thunderbird')
Example #3
0
 def test_ascii(self):
     email = EmailMessage('Subject', 'Content', '*****@*****.**', ['*****@*****.**'])
     message = email.message()
     self.assertEqual(message['Subject'].encode(), 'Subject')
     self.assertEqual(message.get_payload(), 'Content')
     self.assertEqual(message['From'], '*****@*****.**')
     self.assertEqual(message['To'], '*****@*****.**')
Example #4
0
 def test_multiple_recipients(self):
     email = EmailMessage('Subject', 'Content', '*****@*****.**', ['*****@*****.**', '*****@*****.**'])
     message = email.message()
     self.assertEqual(message['Subject'].encode(), 'Subject')
     self.assertEqual(message.get_payload(), 'Content')
     self.assertEqual(message['From'], '*****@*****.**')
     self.assertEqual(message['To'], '[email protected], [email protected]')
Example #5
0
    def test_encoding(self):
        """
        Regression for #12791 - Encode body correctly with other encodings
        than utf-8
        """
        email = EmailMessage('Subject', 'Firstname Sürname is a great guy.',
                             '*****@*****.**', ['*****@*****.**'])
        email.encoding = 'iso-8859-1'
        message = email.message()
        self.assertTrue(message.as_string().startswith(
            'Content-Type: text/plain; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\nSubject: Subject\nFrom: [email protected]\nTo: [email protected]'
        ))
        self.assertEqual(message.get_payload(),
                         'Firstname S=FCrname is a great guy.')

        # Make sure MIME attachments also works correctly with other encodings than utf-8
        text_content = 'Firstname Sürname is a great guy.'
        html_content = '<p>Firstname Sürname is a <strong>great</strong> guy.</p>'
        msg = EmailMultiAlternatives('Subject', text_content,
                                     '*****@*****.**', ['*****@*****.**'])
        msg.encoding = 'iso-8859-1'
        msg.attach_alternative(html_content, "text/html")
        self.assertEqual(
            msg.message().get_payload(0).as_string(),
            'Content-Type: text/plain; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\n\nFirstname S=FCrname is a great guy.'
        )
        self.assertEqual(
            msg.message().get_payload(1).as_string(),
            'Content-Type: text/html; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\n\n<p>Firstname S=FCrname is a <strong>great</strong> guy.</p>'
        )
Example #6
0
 def test_multiple_recipients(self):
     email = EmailMessage('Subject', 'Content', '*****@*****.**',
                          ['*****@*****.**', '*****@*****.**'])
     message = email.message()
     self.assertEqual(message['Subject'].encode(), 'Subject')
     self.assertEqual(message.get_payload(), 'Content')
     self.assertEqual(message['From'], '*****@*****.**')
     self.assertEqual(message['To'], '[email protected], [email protected]')
Example #7
0
 def test_ascii(self):
     email = EmailMessage('Subject', 'Content', '*****@*****.**',
                          ['*****@*****.**'])
     message = email.message()
     self.assertEqual(message['Subject'].encode(), 'Subject')
     self.assertEqual(message.get_payload(), 'Content')
     self.assertEqual(message['From'], '*****@*****.**')
     self.assertEqual(message['To'], '*****@*****.**')
Example #8
0
 def test_dont_mangle_from_in_body(self):
     # Regression for #13433 - Make sure that EmailMessage doesn't mangle
     # 'From ' in message body.
     email = EmailMessage('Subject',
                          'From the future',
                          '*****@*****.**', ['*****@*****.**'],
                          headers={'From': '*****@*****.**'})
     self.assertFalse('>From the future' in email.message().as_string())
Example #9
0
 def test_message_header_overrides(self):
     """
     Specifying dates or message-ids in the extra headers overrides the
     default values (#9233)
     """
     headers = {"date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"}
     email = EmailMessage('subject', 'content', '*****@*****.**', ['*****@*****.**'], headers=headers)
     self.assertEqual(email.message().as_string(), 'Content-Type: text/plain; charset="utf-8"\nMIME-Version: 1.0\nContent-Transfer-Encoding: 7bit\nSubject: subject\nFrom: [email protected]\nTo: [email protected]\ndate: Fri, 09 Nov 2001 01:08:47 -0000\nMessage-ID: foo\n\ncontent')
Example #10
0
 def test_send_verbose_name(self):
     email = EmailMessage("Subject", "Content", '"Firstname Sürname" <*****@*****.**>',
                          ["*****@*****.**"])
     email.send()
     message = self.get_the_message()
     self.assertEqual(message["subject"], "Subject")
     self.assertEqual(message.get_payload(), "Content")
     self.assertEqual(message["from"], "=?utf-8?q?Firstname_S=C3=BCrname?= <*****@*****.**>")
Example #11
0
 def test_unicode_headers(self):
     email = EmailMessage("Gżegżółka", "Content", "*****@*****.**", ["*****@*****.**"],
                          headers={"Sender": '"Firstname Sürname" <*****@*****.**>',
                                   "Comments": 'My Sürname is non-ASCII'})
     message = email.message()
     self.assertEqual(message['Subject'], '=?utf-8?b?R8W8ZWfFvMOzxYJrYQ==?=')
     self.assertEqual(message['Sender'], '=?utf-8?q?Firstname_S=C3=BCrname?= <*****@*****.**>')
     self.assertEqual(message['Comments'], '=?utf-8?q?My_S=C3=BCrname_is_non-ASCII?=')
Example #12
0
 def test_send_verbose_name(self):
     email = EmailMessage("Subject", "Content", '"Firstname Sürname" <*****@*****.**>',
                          ["*****@*****.**"])
     email.send()
     message = self.get_the_message()
     self.assertEqual(message["subject"], "Subject")
     self.assertEqual(message.get_payload(), "Content")
     self.assertEqual(message["from"], "=?utf-8?q?Firstname_S=C3=BCrname?= <*****@*****.**>")
Example #13
0
 def test_send_many(self):
     email1 = EmailMessage('Subject', 'Content1', '*****@*****.**', ['*****@*****.**'])
     email2 = EmailMessage('Subject', 'Content2', '*****@*****.**', ['*****@*****.**'])
     num_sent = get_connection().send_messages([email1, email2])
     self.assertEqual(num_sent, 2)
     messages = self.get_mailbox_content()
     self.assertEqual(len(messages), 2)
     self.assertEqual(messages[0].get_payload(), "Content1")
     self.assertEqual(messages[1].get_payload(), "Content2")
Example #14
0
 def test_from_header(self):
     """
     Make sure we can manually set the From header (#9214)
     """
     email = EmailMessage('Subject',
                          'Content',
                          '*****@*****.**', ['*****@*****.**'],
                          headers={'From': '*****@*****.**'})
     message = email.message()
     self.assertEqual(message['From'], '*****@*****.**')
Example #15
0
 def test_multiple_message_call(self):
     """
     Regression for #13259 - Make sure that headers are not changed when
     calling EmailMessage.message()
     """
     email = EmailMessage('Subject', 'Content', '*****@*****.**', ['*****@*****.**'], headers={'From': '*****@*****.**'})
     message = email.message()
     self.assertEqual(message['From'], '*****@*****.**')
     message = email.message()
     self.assertEqual(message['From'], '*****@*****.**')
Example #16
0
 def test_unicode_address_header(self):
     """
     Regression for #11144 - When a to/from/cc header contains unicode,
     make sure the email addresses are parsed correctly (especially with
     regards to commas)
     """
     email = EmailMessage('Subject', 'Content', '*****@*****.**', ['"Firstname Sürname" <*****@*****.**>', '*****@*****.**'])
     self.assertEqual(email.message()['To'], '=?utf-8?q?Firstname_S=C3=BCrname?= <*****@*****.**>, [email protected]')
     email = EmailMessage('Subject', 'Content', '*****@*****.**', ['"Sürname, Firstname" <*****@*****.**>', '*****@*****.**'])
     self.assertEqual(email.message()['To'], '=?utf-8?q?S=C3=BCrname=2C_Firstname?= <*****@*****.**>, [email protected]')
Example #17
0
 def test_non_ascii_attachment_filename(self):
     """Regression test for Django #14964"""
     headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"}
     subject, from_email, to = 'hello', '*****@*****.**', '*****@*****.**'
     content = 'This is the message.'
     msg = EmailMessage(subject, content, from_email, [to], headers=headers)
     # Unicode in file name
     msg.attach("une pièce jointe.pdf", "%PDF-1.4.%...", mimetype="application/pdf")
     msg_str = msg.message().as_string()
     message = message_from_string(msg_str)
     payload = message.get_payload()
     self.assertEqual(payload[1].get_filename(), 'une pièce jointe.pdf')
Example #18
0
 def test_space_continuation(self):
     """
     Test for space continuation character in long (ascii) subject headers (#7747)
     """
     email = EmailMessage(
         'Long subject lines that get wrapped should use a space continuation character to get expected behavior in Outlook and Thunderbird',
         'Content', '*****@*****.**', ['*****@*****.**'])
     message = email.message()
     self.assertEqual(
         message['Subject'],
         'Long subject lines that get wrapped should use a space continuation\n character to get expected behavior in Outlook and Thunderbird'
     )
Example #19
0
 def test_recipients_as_tuple(self):
     email = EmailMessage('Subject',
                          'Content',
                          '*****@*****.**',
                          ('*****@*****.**', '*****@*****.**'),
                          cc=('*****@*****.**', '*****@*****.**'),
                          bcc=('*****@*****.**', ))
     message = email.message()
     self.assertEqual(message['Cc'], '[email protected], [email protected]')
     self.assertEqual(email.recipients(), [
         '*****@*****.**', '*****@*****.**', '*****@*****.**',
         '*****@*****.**', '*****@*****.**'
     ])
Example #20
0
 def test_multiple_message_call(self):
     """
     Regression for #13259 - Make sure that headers are not changed when
     calling EmailMessage.message()
     """
     email = EmailMessage('Subject',
                          'Content',
                          '*****@*****.**', ['*****@*****.**'],
                          headers={'From': '*****@*****.**'})
     message = email.message()
     self.assertEqual(message['From'], '*****@*****.**')
     message = email.message()
     self.assertEqual(message['From'], '*****@*****.**')
Example #21
0
 def test_custom_backend(self):
     """Test custom backend defined in this suite."""
     conn = get_connection('tests.CustomMail')
     self.assertTrue(hasattr(conn, 'test_outbox'))
     email = EmailMessage('Subject', 'Content', '*****@*****.**', ['*****@*****.**'], headers={'From': '*****@*****.**'})
     conn.send_messages([email])
     self.assertEqual(len(conn.test_outbox), 1)
Example #22
0
 def test_dummy_backend(self):
     """
     Make sure that dummy backends returns correct number of sent messages
     """
     connection = DummyMail()
     email = EmailMessage('Subject', 'Content', '*****@*****.**', ['*****@*****.**'], headers={'From': '*****@*****.**'})
     self.assertEqual(connection.send_messages([email, email, email]), 3)
Example #23
0
    def test_to_header(self):
        """
        Make sure we can manually set the To header (#17444)
        """
        email = EmailMessage('Subject', 'Content', '*****@*****.**',
                             ['*****@*****.**', '*****@*****.**'],
                             headers={'To': '*****@*****.**'})
        message = email.message()
        self.assertEqual(message['To'], '*****@*****.**')
        self.assertEqual(email.to, ['*****@*****.**', '*****@*****.**'])

        # If we don't set the To header manually, it should default to the `to` argument to the constructor
        email = EmailMessage('Subject', 'Content', '*****@*****.**',
                             ['*****@*****.**', '*****@*****.**'])
        message = email.message()
        self.assertEqual(message['To'], '[email protected], [email protected]')
        self.assertEqual(email.to, ['*****@*****.**', '*****@*****.**'])
Example #24
0
 def test_message_header_overrides(self):
     """
     Specifying dates or message-ids in the extra headers overrides the
     default values (#9233)
     """
     headers = {
         "date": "Fri, 09 Nov 2001 01:08:47 -0000",
         "Message-ID": "foo"
     }
     email = EmailMessage('subject',
                          'content',
                          '*****@*****.**', ['*****@*****.**'],
                          headers=headers)
     self.assertEqual(
         email.message().as_string(),
         'Content-Type: text/plain; charset="utf-8"\nMIME-Version: 1.0\nContent-Transfer-Encoding: 7bit\nSubject: subject\nFrom: [email protected]\nTo: [email protected]\ndate: Fri, 09 Nov 2001 01:08:47 -0000\nMessage-ID: foo\n\ncontent'
     )
Example #25
0
 def test_non_ascii_attachment_filename(self):
     """Regression test for Django #14964"""
     headers = {
         "Date": "Fri, 09 Nov 2001 01:08:47 -0000",
         "Message-ID": "foo"
     }
     subject, from_email, to = 'hello', '*****@*****.**', '*****@*****.**'
     content = 'This is the message.'
     msg = EmailMessage(subject, content, from_email, [to], headers=headers)
     # Unicode in file name
     msg.attach(u"une pièce jointe.pdf",
                "%PDF-1.4.%...",
                mimetype="application/pdf")
     msg_str = msg.message().as_string()
     message = message_from_string(msg_str)
     payload = message.get_payload()
     self.assertEqual(payload[1].get_filename(), u'une pièce jointe.pdf')
Example #26
0
 def test_unicode_headers(self):
     email = EmailMessage(u"Gżegżółka",
                          "Content",
                          "*****@*****.**", ["*****@*****.**"],
                          headers={
                              "Sender":
                              '"Firstname Sürname" <*****@*****.**>',
                              "Comments": 'My Sürname is non-ASCII'
                          })
     message = email.message()
     self.assertEqual(message['Subject'],
                      '=?utf-8?b?R8W8ZWfFvMOzxYJrYQ==?=')
     self.assertEqual(
         message['Sender'],
         '=?utf-8?q?Firstname_S=C3=BCrname?= <*****@*****.**>')
     self.assertEqual(message['Comments'],
                      '=?utf-8?q?My_S=C3=BCrname_is_non-ASCII?=')
Example #27
0
 def test_message_cc_header(self):
     """
     Regression test for Django #7722
     """
     email = EmailMessage('Subject', 'Content', '*****@*****.**', ['*****@*****.**'], cc=['*****@*****.**'])
     get_connection().send_messages([email])
     message = self.get_the_message()
     self.assertStartsWith(message.as_string(), 'Content-Type: text/plain; charset="utf-8"\nMIME-Version: 1.0\nContent-Transfer-Encoding: 7bit\nSubject: Subject\nFrom: [email protected]\nTo: [email protected]\nCc: [email protected]\nDate: ')
Example #28
0
    def test_file_sessions(self):
        """Make sure opening a connection creates a new file"""
        msg = EmailMessage('Subject',
                           'Content',
                           '*****@*****.**', ['*****@*****.**'],
                           headers={'From': '*****@*****.**'})
        connection = get_connection()
        connection.send_messages([msg])

        self.assertEqual(len(os.listdir(self.tmp_dir)), 1)
        message = message_from_file(
            open(os.path.join(self.tmp_dir,
                              os.listdir(self.tmp_dir)[0])))
        self.assertEqual(message.get_content_type(), 'text/plain')
        self.assertEqual(message.get('subject'), 'Subject')
        self.assertEqual(message.get('from'), '*****@*****.**')
        self.assertEqual(message.get('to'), '*****@*****.**')

        connection2 = get_connection()
        connection2.send_messages([msg])
        self.assertEqual(len(os.listdir(self.tmp_dir)), 2)

        connection.send_messages([msg])
        self.assertEqual(len(os.listdir(self.tmp_dir)), 2)

        msg.connection = get_connection()
        self.assertTrue(connection.open())
        msg.send()
        self.assertEqual(len(os.listdir(self.tmp_dir)), 3)
        msg.send()
        self.assertEqual(len(os.listdir(self.tmp_dir)), 3)
Example #29
0
 def test_send(self):
     email = EmailMessage('Subject', 'Content', '*****@*****.**', ['*****@*****.**'])
     num_sent = get_connection().send_messages([email])
     self.assertEqual(num_sent, 1)
     message = self.get_the_message()
     self.assertEqual(message["subject"], "Subject")
     self.assertEqual(message.get_payload(), "Content")
     self.assertEqual(message["from"], "*****@*****.**")
     self.assertEqual(message.get_all("to"), ["*****@*****.**"])
Example #30
0
    def test_encoding(self):
        """
        Regression for #12791 - Encode body correctly with other encodings
        than utf-8
        """
        email = EmailMessage('Subject', 'Firstname Sürname is a great guy.', '*****@*****.**', ['*****@*****.**'])
        email.encoding = 'iso-8859-1'
        message = email.message()
        self.assertTrue(message.as_string().startswith('Content-Type: text/plain; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\nSubject: Subject\nFrom: [email protected]\nTo: [email protected]'))
        self.assertEqual(message.get_payload(), 'Firstname S=FCrname is a great guy.')

        # Make sure MIME attachments also works correctly with other encodings than utf-8
        text_content = 'Firstname Sürname is a great guy.'
        html_content = '<p>Firstname Sürname is a <strong>great</strong> guy.</p>'
        msg = EmailMultiAlternatives('Subject', text_content, '*****@*****.**', ['*****@*****.**'])
        msg.encoding = 'iso-8859-1'
        msg.attach_alternative(html_content, "text/html")
        self.assertEqual(msg.message().get_payload(0).as_string(), 'Content-Type: text/plain; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\n\nFirstname S=FCrname is a great guy.')
        self.assertEqual(msg.message().get_payload(1).as_string(), 'Content-Type: text/html; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\n\n<p>Firstname S=FCrname is a <strong>great</strong> guy.</p>')
Example #31
0
    def test_idn_send(self):
        """
        Regression test for Django #14301
        """
        self.assertTrue(send_mail('Subject', 'Content', 'from@öäü.com', [u'to@öäü.com']))
        message = self.get_the_message()
        self.assertEqual(message.get('subject'), 'Subject')
        self.assertEqual(message.get('from'), '*****@*****.**')
        self.assertEqual(message.get('to'), '*****@*****.**')

        self.flush_mailbox()
        m = EmailMessage('Subject', 'Content', 'from@öäü.com',
                     [u'to@öäü.com'], cc=[u'cc@öäü.com'])
        m.send()
        message = self.get_the_message()
        self.assertEqual(message.get('subject'), 'Subject')
        self.assertEqual(message.get('from'), '*****@*****.**')
        self.assertEqual(message.get('to'), '*****@*****.**')
        self.assertEqual(message.get('cc'), '*****@*****.**')
Example #32
0
    def test_idn_send(self):
        """
        Regression test for Django #14301
        """
        self.assertTrue(send_mail('Subject', 'Content', 'from@öäü.com', ['to@öäü.com']))
        message = self.get_the_message()
        self.assertEqual(message.get('subject'), 'Subject')
        self.assertEqual(message.get('from'), '*****@*****.**')
        self.assertEqual(message.get('to'), '*****@*****.**')

        self.flush_mailbox()
        m = EmailMessage('Subject', 'Content', 'from@öäü.com',
                     ['to@öäü.com'], cc=['cc@öäü.com'])
        m.send()
        message = self.get_the_message()
        self.assertEqual(message.get('subject'), 'Subject')
        self.assertEqual(message.get('from'), '*****@*****.**')
        self.assertEqual(message.get('to'), '*****@*****.**')
        self.assertEqual(message.get('cc'), '*****@*****.**')
Example #33
0
 def test_locmem_shared_messages(self):
     """
     Make sure that the locmen backend populates the outbox.
     """
     connection = Mail()
     connection2 = Mail()
     email = EmailMessage('Subject', 'Content', '*****@*****.**', ['*****@*****.**'], headers={'From': '*****@*****.**'})
     connection.send_messages([email])
     connection2.send_messages([email])
     self.assertEqual(len(mail.outbox), 2)
Example #34
0
    def test_to_header(self):
        """
        Make sure we can manually set the To header (#17444)
        """
        email = EmailMessage(
            'Subject',
            'Content',
            '*****@*****.**',
            ['*****@*****.**', '*****@*****.**'],
            headers={'To': '*****@*****.**'})
        message = email.message()
        self.assertEqual(message['To'], '*****@*****.**')
        self.assertEqual(
            email.to,
            ['*****@*****.**', '*****@*****.**'])

        # If we don't set the To header manually, it should default to the `to` argument to the constructor
        email = EmailMessage(
            'Subject', 'Content', '*****@*****.**',
            ['*****@*****.**', '*****@*****.**'])
        message = email.message()
        self.assertEqual(
            message['To'],
            '[email protected], [email protected]')
        self.assertEqual(
            email.to,
            ['*****@*****.**', '*****@*****.**'])
Example #35
0
    def test_file_sessions(self):
        """Make sure opening a connection creates a new file"""
        msg = EmailMessage('Subject', 'Content', '*****@*****.**', ['*****@*****.**'], headers={'From': '*****@*****.**'})
        connection = get_connection()
        connection.send_messages([msg])

        self.assertEqual(len(os.listdir(self.tmp_dir)), 1)
        message = message_from_file(open(os.path.join(self.tmp_dir, os.listdir(self.tmp_dir)[0])))
        self.assertEqual(message.get_content_type(), 'text/plain')
        self.assertEqual(message.get('subject'), 'Subject')
        self.assertEqual(message.get('from'), '*****@*****.**')
        self.assertEqual(message.get('to'), '*****@*****.**')

        connection2 = get_connection()
        connection2.send_messages([msg])
        self.assertEqual(len(os.listdir(self.tmp_dir)), 2)

        connection.send_messages([msg])
        self.assertEqual(len(os.listdir(self.tmp_dir)), 2)

        msg.connection = get_connection()
        self.assertTrue(connection.open())
        msg.send()
        self.assertEqual(len(os.listdir(self.tmp_dir)), 3)
        msg.send()
        self.assertEqual(len(os.listdir(self.tmp_dir)), 3)
Example #36
0
    def test_cc(self):
        """Regression test for Django #7722"""
        email = EmailMessage('Subject', 'Content', '*****@*****.**', ['*****@*****.**'], cc=['*****@*****.**'])
        message = email.message()
        self.assertEqual(message['Cc'], '*****@*****.**')
        self.assertEqual(email.recipients(), ['*****@*****.**', '*****@*****.**'])

        # Test multiple CC with multiple To
        email = EmailMessage('Subject', 'Content', '*****@*****.**', ['*****@*****.**', '*****@*****.**'], cc=['*****@*****.**', '*****@*****.**'])
        message = email.message()
        self.assertEqual(message['Cc'], '[email protected], [email protected]')
        self.assertEqual(email.recipients(), ['*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**'])

        # Testing with Bcc
        email = EmailMessage('Subject', 'Content', '*****@*****.**', ['*****@*****.**', '*****@*****.**'], cc=['*****@*****.**', '*****@*****.**'], bcc=['*****@*****.**'])
        message = email.message()
        self.assertEqual(message['Cc'], '[email protected], [email protected]')
        self.assertEqual(email.recipients(), ['*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**'])
Example #37
0
    def test_dont_base64_encode(self):
        # Ticket #3472
        # Shouldn't use Base64 encoding at all
        msg = EmailMessage('Subject', 'UTF-8 encoded body', '*****@*****.**', ['*****@*****.**'], headers={'From': '*****@*****.**'})
        self.assertFalse('Content-Transfer-Encoding: base64' in msg.message().as_string())

        # Ticket #11212
        # Shouldn't use quoted printable, should detect it can represent content with 7 bit data
        msg = EmailMessage('Subject', 'Body with only ASCII characters.', '*****@*****.**', ['*****@*****.**'], headers={'From': '*****@*****.**'})
        s = msg.message().as_string()
        self.assertFalse('Content-Transfer-Encoding: quoted-printable' in s)
        self.assertTrue('Content-Transfer-Encoding: 7bit' in s)

        # Shouldn't use quoted printable, should detect it can represent content with 8 bit data
        msg = EmailMessage('Subject', 'Body with latin characters: àáä.', '*****@*****.**', ['*****@*****.**'], headers={'From': '*****@*****.**'})
        s = msg.message().as_string()
        self.assertFalse('Content-Transfer-Encoding: quoted-printable' in s)
        self.assertTrue('Content-Transfer-Encoding: 8bit' in s)

        msg = EmailMessage('Subject', 'Body with non latin characters: А Б В Г Д Е Ж Ѕ З И І К Л М Н О П.', '*****@*****.**', ['*****@*****.**'], headers={'From': '*****@*****.**'})
        s = msg.message().as_string()
        self.assertFalse('Content-Transfer-Encoding: quoted-printable' in s)
        self.assertTrue('Content-Transfer-Encoding: 8bit' in s)
Example #38
0
 def test_unicode_address_header(self):
     """
     Regression for #11144 - When a to/from/cc header contains unicode,
     make sure the email addresses are parsed correctly (especially with
     regards to commas)
     """
     email = EmailMessage(
         'Subject', 'Content', '*****@*****.**',
         ['"Firstname Sürname" <*****@*****.**>', '*****@*****.**'])
     self.assertEqual(
         email.message()['To'],
         '=?utf-8?q?Firstname_S=C3=BCrname?= <*****@*****.**>, [email protected]'
     )
     email = EmailMessage(
         'Subject', 'Content', '*****@*****.**',
         ['"Sürname, Firstname" <*****@*****.**>', '*****@*****.**'])
     self.assertEqual(
         email.message()['To'],
         '=?utf-8?q?S=C3=BCrname=2C_Firstname?= <*****@*****.**>, [email protected]'
     )
Example #39
0
    def test_cc(self):
        """Regression test for Django #7722"""
        email = EmailMessage('Subject',
                             'Content',
                             '*****@*****.**', ['*****@*****.**'],
                             cc=['*****@*****.**'])
        message = email.message()
        self.assertEqual(message['Cc'], '*****@*****.**')
        self.assertEqual(email.recipients(),
                         ['*****@*****.**', '*****@*****.**'])

        # Test multiple CC with multiple To
        email = EmailMessage('Subject',
                             'Content',
                             '*****@*****.**',
                             ['*****@*****.**', '*****@*****.**'],
                             cc=['*****@*****.**', '*****@*****.**'])
        message = email.message()
        self.assertEqual(message['Cc'], '[email protected], [email protected]')
        self.assertEqual(email.recipients(), [
            '*****@*****.**', '*****@*****.**', '*****@*****.**',
            '*****@*****.**'
        ])

        # Testing with Bcc
        email = EmailMessage('Subject',
                             'Content',
                             '*****@*****.**',
                             ['*****@*****.**', '*****@*****.**'],
                             cc=['*****@*****.**', '*****@*****.**'],
                             bcc=['*****@*****.**'])
        message = email.message()
        self.assertEqual(message['Cc'], '[email protected], [email protected]')
        self.assertEqual(email.recipients(), [
            '*****@*****.**', '*****@*****.**', '*****@*****.**',
            '*****@*****.**', '*****@*****.**'
        ])
Example #40
0
def forge_email(fromaddr,
                toaddr,
                subject,
                content,
                html_content='',
                html_images=None,
                usebcc=False,
                header=None,
                footer=None,
                html_header=None,
                html_footer=None,
                ln=CFG_SITE_LANG,
                charset=None,
                replytoaddr="",
                attachments=None):
    """Prepare email. Add header and footer if needed.
    @param fromaddr: [string] sender
    @param toaddr: [string or list-of-strings] list of receivers (if string, then
                   receivers are separated by ',')
    @param usebcc: [bool] True for using Bcc in place of To
    @param subject: [string] subject of the email
    @param content: [string] content of the email
    @param html_content: [string] html version of the email
    @param html_images: [dict] dictionary of image id, image path
    @param header: [string] None for the default header
    @param footer: [string] None for the default footer
    @param ln: language
    @charset: [string] the content charset. By default is None which means
    to try to encode the email as ascii, then latin1 then utf-8.
    @param replytoaddr: [string or list-of-strings] to be used for the
                        reply-to header of the email (if string, then
                        receivers are separated by ',')
    @param attachments: list of paths of files to be attached. Alternatively,
        every element of the list could be a tuple: (filename, mimetype)
    @return: forged email as a string"""
    if html_images is None:
        html_images = {}

    content = render_template_to_string('mail_text.tpl',
                                        content=content,
                                        header=header,
                                        footer=footer)

    if type(toaddr) is not str:
        toaddr = ','.join(toaddr)

    if type(replytoaddr) is not str:
        replytoaddr = ','.join(replytoaddr)

    toaddr = remove_temporary_emails(toaddr)

    headers = {}
    kwargs = {'to': [], 'cc': [], 'bcc': []}

    if replytoaddr:
        headers['Reply-To'] = replytoaddr
    if usebcc:
        headers['Bcc'] = toaddr
        kwargs['bcc'] = toaddr.split(',')
        kwargs['to'] = ['Undisclosed.Recipients:']
    else:
        kwargs['to'] = toaddr.split(',')
    headers['From'] = fromaddr
    headers['Date'] = formatdate(localtime=True)
    headers['User-Agent'] = 'Invenio %s at %s' % (CFG_VERSION, CFG_SITE_URL)

    if html_content:
        html_content = render_template_to_string('mail_html.tpl',
                                                 content=html_content,
                                                 header=html_header,
                                                 footer=html_footer)

        msg_root = EmailMultiAlternatives(subject=subject,
                                          body=content,
                                          from_email=fromaddr,
                                          headers=headers,
                                          **kwargs)
        msg_root.attach_alternative(html_content, "text/html")

        #if not html_images:
        #    # No image? Attach the HTML to the root
        #    msg_root.attach(msg_text)
        #else:
        if html_images:
            # Image(s)? Attach the HTML and image(s) as children of a
            # "related" block
            msg_related = MIMEMultipart('related')
            #msg_related.attach(msg_text)
            for image_id, image_path in html_images.iteritems():
                attach_embed_image(msg_related, image_id, image_path)
            msg_root.attach(msg_related)
    else:
        msg_root = EmailMessage(subject=subject,
                                body=content,
                                from_email=fromaddr,
                                headers=headers,
                                **kwargs)

    if attachments:
        from invenio.bibdocfile import _mimes, guess_format_from_url
        #old_msg_root = msg_root
        #msg_root = MIMEMultipart()
        #msg_root.attach(old_msg_root)
        for attachment in attachments:
            try:
                mime = None
                if type(attachment) in (list, tuple):
                    attachment, mime = attachment
                if mime is None:
                    ## Automatic guessing of mimetype
                    mime = _mimes.guess_type(attachment)[0]
                if mime is None:
                    ext = guess_format_from_url(attachment)
                    mime = _mimes.guess_type("foo" + ext)[0]
                if not mime:
                    mime = 'application/octet-stream'
                part = MIMEBase(*mime.split('/', 1))
                part.set_payload(open(attachment, 'rb').read())
                Encoders.encode_base64(part)
                part.add_header(
                    'Content-Disposition',
                    'attachment; filename="%s"' % os.path.basename(attachment))
                msg_root.attach(part)
            except:
                register_exception(alert_admin=True,
                                   prefix="Can't attach %s" % attachment)

    return msg_root
Example #41
0
    def test_dont_base64_encode(self):
        # Ticket #3472
        # Shouldn't use Base64 encoding at all
        msg = EmailMessage('Subject',
                           'UTF-8 encoded body',
                           '*****@*****.**', ['*****@*****.**'],
                           headers={'From': '*****@*****.**'})
        self.assertFalse(
            'Content-Transfer-Encoding: base64' in msg.message().as_string())

        # Ticket #11212
        # Shouldn't use quoted printable, should detect it can represent content with 7 bit data
        msg = EmailMessage('Subject',
                           'Body with only ASCII characters.',
                           '*****@*****.**', ['*****@*****.**'],
                           headers={'From': '*****@*****.**'})
        s = msg.message().as_string()
        self.assertFalse('Content-Transfer-Encoding: quoted-printable' in s)
        self.assertTrue('Content-Transfer-Encoding: 7bit' in s)

        # Shouldn't use quoted printable, should detect it can represent content with 8 bit data
        msg = EmailMessage('Subject',
                           'Body with latin characters: àáä.',
                           '*****@*****.**', ['*****@*****.**'],
                           headers={'From': '*****@*****.**'})
        s = msg.message().as_string()
        self.assertFalse('Content-Transfer-Encoding: quoted-printable' in s)
        self.assertTrue('Content-Transfer-Encoding: 8bit' in s)

        msg = EmailMessage(
            'Subject',
            u'Body with non latin characters: А Б В Г Д Е Ж Ѕ З И І К Л М Н О П.',
            '*****@*****.**', ['*****@*****.**'],
            headers={'From': '*****@*****.**'})
        s = msg.message().as_string()
        self.assertFalse('Content-Transfer-Encoding: quoted-printable' in s)
        self.assertTrue('Content-Transfer-Encoding: 8bit' in s)
Example #42
0
 def test_header_injection(self):
     email = EmailMessage('Subject\nInjection Test', 'Content',
                          '*****@*****.**', ['*****@*****.**'])
     self.assertRaises(BadHeaderError, email.message)
Example #43
0
 def test_recipients_as_tuple(self):
     email = EmailMessage('Subject', 'Content', '*****@*****.**', ('*****@*****.**', '*****@*****.**'), cc=('*****@*****.**', '*****@*****.**'), bcc=('*****@*****.**',))
     message = email.message()
     self.assertEqual(message['Cc'], '[email protected], [email protected]')
     self.assertEqual(email.recipients(), ['*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**'])
Example #44
0
 def test_dont_mangle_from_in_body(self):
     # Regression for #13433 - Make sure that EmailMessage doesn't mangle
     # 'From ' in message body.
     email = EmailMessage('Subject', 'From the future', '*****@*****.**', ['*****@*****.**'], headers={'From': '*****@*****.**'})
     self.assertFalse('>From the future' in email.message().as_string())