Python email.mime.image.MIMEImage() Examples

The following are 30 code examples of email.mime.image.MIMEImage(). 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.image , or try the search function .
Example #1
Source File: mixins.py    From adhocracy4 with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_attachments(self):
        attachments = super().get_attachments()
        filename = (
            finders.find('images/email_logo.png')
            or finders.find('images/email_logo.svg')
        )
        if filename:
            if filename.endswith('.png'):
                imagetype = 'png'
            else:
                imagetype = 'svg+xml'

            with open(filename, 'rb') as f:
                logo = MIMEImage(f.read(), imagetype)

            logo.add_header('Content-ID', '<{}>'.format('logo'))
            return attachments + [logo]
        return attachments 
Example #2
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._au.add_header('Content-Disposition', 'attachment',
                            filename='audiotest.au')
        eq(self._au['content-disposition'],
           'attachment; filename="audiotest.au"')
        eq(self._au.get_params(header='content-disposition'),
           [('attachment', ''), ('filename', 'audiotest.au')])
        eq(self._au.get_param('filename', header='content-disposition'),
           'audiotest.au')
        missing = []
        eq(self._au.get_param('attachment', header='content-disposition'), '')
        self.assertIs(self._au.get_param('foo', failobj=missing,
                                         header='content-disposition'),
                      missing)
        # Try some missing stuff
        self.assertIs(self._au.get_param('foobar', missing), missing)
        self.assertIs(self._au.get_param('attachment', missing,
                                         header='foobar'), missing)



# Test the basic MIMEImage class 
Example #3
Source File: test_email_renamed.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test__all__(self):
        module = __import__('email')
        # Can't use sorted() here due to Python 2.3 compatibility
        all = module.__all__[:]
        all.sort()
        self.assertEqual(all, [
            # Old names
            'Charset', 'Encoders', 'Errors', 'Generator',
            'Header', 'Iterators', 'MIMEAudio', 'MIMEBase',
            'MIMEImage', 'MIMEMessage', 'MIMEMultipart',
            'MIMENonMultipart', 'MIMEText', 'Message',
            'Parser', 'Utils', 'base64MIME',
            # new names
            'base64mime', 'charset', 'encoders', 'errors', 'generator',
            'header', 'iterators', 'message', 'message_from_file',
            'message_from_string', 'mime', 'parser',
            'quopriMIME', 'quoprimime', 'utils',
            ]) 
Example #4
Source File: test_email_renamed.py    From CTFCrackTools-V2 with GNU General Public License v3.0 6 votes vote down vote up
def test__all__(self):
        module = __import__('email')
        # Can't use sorted() here due to Python 2.3 compatibility
        all = module.__all__[:]
        all.sort()
        self.assertEqual(all, [
            # Old names
            'Charset', 'Encoders', 'Errors', 'Generator',
            'Header', 'Iterators', 'MIMEAudio', 'MIMEBase',
            'MIMEImage', 'MIMEMessage', 'MIMEMultipart',
            'MIMENonMultipart', 'MIMEText', 'Message',
            'Parser', 'Utils', 'base64MIME',
            # new names
            'base64mime', 'charset', 'encoders', 'errors', 'generator',
            'header', 'iterators', 'message', 'message_from_file',
            'message_from_string', 'mime', 'parser',
            'quopriMIME', 'quoprimime', 'utils',
            ]) 
Example #5
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._au.add_header('Content-Disposition', 'attachment',
                            filename='audiotest.au')
        eq(self._au['content-disposition'],
           'attachment; filename="audiotest.au"')
        eq(self._au.get_params(header='content-disposition'),
           [('attachment', ''), ('filename', 'audiotest.au')])
        eq(self._au.get_param('filename', header='content-disposition'),
           'audiotest.au')
        missing = []
        eq(self._au.get_param('attachment', header='content-disposition'), '')
        unless(self._au.get_param('foo', failobj=missing,
                                  header='content-disposition') is missing)
        # Try some missing stuff
        unless(self._au.get_param('foobar', missing) is missing)
        unless(self._au.get_param('attachment', missing,
                                  header='foobar') is missing)



# Test the basic MIMEImage class 
Example #6
Source File: test_email_renamed.py    From CTFCrackTools-V2 with GNU General Public License v3.0 6 votes vote down vote up
def test__all__(self):
        module = __import__('email')
        # Can't use sorted() here due to Python 2.3 compatibility
        all = module.__all__[:]
        all.sort()
        self.assertEqual(all, [
            # Old names
            'Charset', 'Encoders', 'Errors', 'Generator',
            'Header', 'Iterators', 'MIMEAudio', 'MIMEBase',
            'MIMEImage', 'MIMEMessage', 'MIMEMultipart',
            'MIMENonMultipart', 'MIMEText', 'Message',
            'Parser', 'Utils', 'base64MIME',
            # new names
            'base64mime', 'charset', 'encoders', 'errors', 'generator',
            'header', 'iterators', 'message', 'message_from_file',
            'message_from_string', 'mime', 'parser',
            'quopriMIME', 'quoprimime', 'utils',
            ]) 
Example #7
Source File: email_tests.py    From incubator-superset with Apache License 2.0 6 votes vote down vote up
def test_send_smtp_inline_images(self, mock_send_mime):
        image = read_fixture("sample.png")
        utils.send_email_smtp(
            "to", "subject", "content", app.config, images=dict(blah=image)
        )
        assert mock_send_mime.called
        call_args = mock_send_mime.call_args[0]
        logger.debug(call_args)
        assert call_args[0] == app.config["SMTP_MAIL_FROM"]
        assert call_args[1] == ["to"]
        msg = call_args[2]
        assert msg["Subject"] == "subject"
        assert msg["From"] == app.config["SMTP_MAIL_FROM"]
        assert len(msg.get_payload()) == 2
        mimeapp = MIMEImage(image)
        assert msg.get_payload()[-1].get_payload() == mimeapp.get_payload() 
Example #8
Source File: test_email_renamed.py    From CTFCrackTools-V2 with GNU General Public License v3.0 6 votes vote down vote up
def test_add_header(self):
        eq = self.assertEqual
        unless = self.assertTrue
        self._au.add_header('Content-Disposition', 'attachment',
                            filename='audiotest.au')
        eq(self._au['content-disposition'],
           'attachment; filename="audiotest.au"')
        eq(self._au.get_params(header='content-disposition'),
           [('attachment', ''), ('filename', 'audiotest.au')])
        eq(self._au.get_param('filename', header='content-disposition'),
           'audiotest.au')
        missing = []
        eq(self._au.get_param('attachment', header='content-disposition'), '')
        unless(self._au.get_param('foo', failobj=missing,
                                  header='content-disposition') is missing)
        # Try some missing stuff
        unless(self._au.get_param('foobar', missing) is missing)
        unless(self._au.get_param('attachment', missing,
                                  header='foobar') is missing)



# Test the basic MIMEImage class 
Example #9
Source File: mail.py    From cmdb with GNU General Public License v2.0 6 votes vote down vote up
def send_mail(sender, receiver, subject, content, ctype="html", pics=()):
    """subject and body are unicode objects"""
    if not sender:
        sender = current_app.config.get("DEFAULT_MAIL_SENDER")
    smtp_server = current_app.config.get("MAIL_SERVER")
    if ctype == "html":
        msg = MIMEText(content, 'html', 'utf-8')
    else:
        msg = MIMEText(content, 'plain', 'utf-8')

    if len(pics) != 0:
        msg_root = MIMEMultipart('related')
        msg_text = MIMEText(content, 'html', 'utf-8')
        msg_root.attach(msg_text)
        i = 1
        for pic in pics:
            fp = open(pic, "rb")
            image = MIMEImage(fp.read())
            fp.close()
            image.add_header('Content-ID', '<img%02d>' % i)
            msg_root.attach(image)
            i += 1
        msg = msg_root

    msg['Subject'] = Header(subject, 'utf-8')
    msg['From'] = sender
    msg['To'] = ';'.join(receiver)
    msg['Message-ID'] = Utils.make_msgid()
    msg['date'] = time.strftime('%a, %d %b %Y %H:%M:%S %z')

    smtp = smtplib.SMTP()
    smtp.connect(smtp_server, 25)
    username, password = current_app.config.get("MAIL_USERNAME"), current_app.config.get("MAIL_PASSWORD")
    if username and password:
        smtp.login(username, password)
    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.quit() 
Example #10
Source File: test_email_renamed.py    From BinderFilter with MIT License 6 votes vote down vote up
def test__all__(self):
        module = __import__('email')
        # Can't use sorted() here due to Python 2.3 compatibility
        all = module.__all__[:]
        all.sort()
        self.assertEqual(all, [
            # Old names
            'Charset', 'Encoders', 'Errors', 'Generator',
            'Header', 'Iterators', 'MIMEAudio', 'MIMEBase',
            'MIMEImage', 'MIMEMessage', 'MIMEMultipart',
            'MIMENonMultipart', 'MIMEText', 'Message',
            'Parser', 'Utils', 'base64MIME',
            # new names
            'base64mime', 'charset', 'encoders', 'errors', 'generator',
            'header', 'iterators', 'message', 'message_from_file',
            'message_from_string', 'mime', 'parser',
            'quopriMIME', 'quoprimime', 'utils',
            ]) 
Example #11
Source File: test_email_renamed.py    From oss-ftp with MIT License 6 votes vote down vote up
def test__all__(self):
        module = __import__('email')
        # Can't use sorted() here due to Python 2.3 compatibility
        all = module.__all__[:]
        all.sort()
        self.assertEqual(all, [
            # Old names
            'Charset', 'Encoders', 'Errors', 'Generator',
            'Header', 'Iterators', 'MIMEAudio', 'MIMEBase',
            'MIMEImage', 'MIMEMessage', 'MIMEMultipart',
            'MIMENonMultipart', 'MIMEText', 'Message',
            'Parser', 'Utils', 'base64MIME',
            # new names
            'base64mime', 'charset', 'encoders', 'errors', 'generator',
            'header', 'iterators', 'message', 'message_from_file',
            'message_from_string', 'mime', 'parser',
            'quopriMIME', 'quoprimime', 'utils',
            ]) 
Example #12
Source File: test_email_renamed.py    From medicare-demo with Apache License 2.0 6 votes vote down vote up
def test__all__(self):
        module = __import__('email')
        # Can't use sorted() here due to Python 2.3 compatibility
        all = module.__all__[:]
        all.sort()
        self.assertEqual(all, [
            # Old names
            'Charset', 'Encoders', 'Errors', 'Generator',
            'Header', 'Iterators', 'MIMEAudio', 'MIMEBase',
            'MIMEImage', 'MIMEMessage', 'MIMEMultipart',
            'MIMENonMultipart', 'MIMEText', 'Message',
            'Parser', 'Utils', 'base64MIME',
            # new names
            'base64mime', 'charset', 'encoders', 'errors', 'generator',
            'header', 'iterators', 'message', 'message_from_file',
            'message_from_string', 'mime', 'parser',
            'quopriMIME', 'quoprimime', 'utils',
            ]) 
Example #13
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._au.add_header('Content-Disposition', 'attachment',
                            filename='audiotest.au')
        eq(self._au['content-disposition'],
           'attachment; filename="audiotest.au"')
        eq(self._au.get_params(header='content-disposition'),
           [('attachment', ''), ('filename', 'audiotest.au')])
        eq(self._au.get_param('filename', header='content-disposition'),
           'audiotest.au')
        missing = []
        eq(self._au.get_param('attachment', header='content-disposition'), '')
        unless(self._au.get_param('foo', failobj=missing,
                                  header='content-disposition') is missing)
        # Try some missing stuff
        unless(self._au.get_param('foobar', missing) is missing)
        unless(self._au.get_param('attachment', missing,
                                  header='foobar') is missing)



# Test the basic MIMEImage class 
Example #14
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._au.add_header('Content-Disposition', 'attachment',
                            filename='audiotest.au')
        eq(self._au['content-disposition'],
           'attachment; filename="audiotest.au"')
        eq(self._au.get_params(header='content-disposition'),
           [('attachment', ''), ('filename', 'audiotest.au')])
        eq(self._au.get_param('filename', header='content-disposition'),
           'audiotest.au')
        missing = []
        eq(self._au.get_param('attachment', header='content-disposition'), '')
        self.assertIs(self._au.get_param('foo', failobj=missing,
                                         header='content-disposition'),
                      missing)
        # Try some missing stuff
        self.assertIs(self._au.get_param('foobar', missing), missing)
        self.assertIs(self._au.get_param('attachment', missing,
                                         header='foobar'), missing)



# Test the basic MIMEImage class 
Example #15
Source File: notify.py    From HomeAssistantConfig with MIT License 6 votes vote down vote up
def _build_html_msg(text, html, images):
    """Build Multipart message with in-line images and rich HTML (UTF-8)."""
    _LOGGER.debug("Building HTML rich email")
    msg = MIMEMultipart('related')
    alternative = MIMEMultipart('alternative')
    alternative.attach(MIMEText(text, _charset='utf-8'))
    alternative.attach(MIMEText(html, ATTR_HTML, _charset='utf-8'))
    msg.attach(alternative)

    for atch_num, atch_name in enumerate(images):
        name = os.path.basename(atch_name)
        try:
            with open(atch_name, 'rb') as attachment_file:
                attachment = MIMEImage(attachment_file.read(), filename=name)
            msg.attach(attachment)
            attachment.add_header('Content-ID', '<{}>'.format(name))
        except FileNotFoundError:
            _LOGGER.warning("Attachment %s [#%s] not found. Skipping",
                            atch_name, atch_num)
    return msg 
Example #16
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._au.add_header('Content-Disposition', 'attachment',
                            filename='audiotest.au')
        eq(self._au['content-disposition'],
           'attachment; filename="audiotest.au"')
        eq(self._au.get_params(header='content-disposition'),
           [('attachment', ''), ('filename', 'audiotest.au')])
        eq(self._au.get_param('filename', header='content-disposition'),
           'audiotest.au')
        missing = []
        eq(self._au.get_param('attachment', header='content-disposition'), '')
        self.assertIs(self._au.get_param('foo', failobj=missing,
                                         header='content-disposition'), missing)
        # Try some missing stuff
        self.assertIs(self._au.get_param('foobar', missing), missing)
        self.assertIs(self._au.get_param('attachment', missing,
                                         header='foobar'), missing)



# Test the basic MIMEImage class 
Example #17
Source File: test_email_renamed.py    From datafari with Apache License 2.0 6 votes vote down vote up
def test__all__(self):
        module = __import__('email')
        # Can't use sorted() here due to Python 2.3 compatibility
        all = module.__all__[:]
        all.sort()
        self.assertEqual(all, [
            # Old names
            'Charset', 'Encoders', 'Errors', 'Generator',
            'Header', 'Iterators', 'MIMEAudio', 'MIMEBase',
            'MIMEImage', 'MIMEMessage', 'MIMEMultipart',
            'MIMENonMultipart', 'MIMEText', 'Message',
            'Parser', 'Utils', 'base64MIME',
            # new names
            'base64mime', 'charset', 'encoders', 'errors', 'generator',
            'header', 'iterators', 'message', 'message_from_file',
            'message_from_string', 'mime', 'parser',
            'quopriMIME', 'quoprimime', 'utils',
            ]) 
Example #18
Source File: mail.py    From Kairos with GNU General Public License v3.0 6 votes vote down vote up
def generate_list_entry(mime_images, alert, screenshots, filenames, url, count):
    result = '<hr><h3>' + alert + '</h3><h4>Alert generated on chart: <a href="' + url + '">' + url + '<a></h4>'
    if len(screenshots) > 0:
        for chart in screenshots:
            result += '<p><a href="' + chart + '"><img src="' + screenshots[chart] + '"/></a><br/><a href="'+screenshots[chart]+'">' + screenshots[chart] + '</a></p>'
    elif len(filenames) > 0:
        for chart in filenames:
            try:
                screenshot_id = str(count + 1)
                fp = open(filenames[chart], 'rb')
                mime_image = MIMEImage(fp.read())
                fp.close()
                mime_image.add_header('Content-ID', '<screenshot' + screenshot_id + '>')
                mime_images.append(mime_image)
                result += '<p><a href="' + chart + '"><img src="cid:screenshot' + screenshot_id + '"/></a><br/>' + filenames[chart] + '</p>'
            except Exception as send_mail_error:
                log.exception(send_mail_error)
                result += '<p><a href="' + url + '">Error embedding screenshot: ' + filenames[chart] + '</a><br/>' + filenames[chart] + '</p>'
    return result 
Example #19
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._au.add_header('Content-Disposition', 'attachment',
                            filename='audiotest.au')
        eq(self._au['content-disposition'],
           'attachment; filename="audiotest.au"')
        eq(self._au.get_params(header='content-disposition'),
           [('attachment', ''), ('filename', 'audiotest.au')])
        eq(self._au.get_param('filename', header='content-disposition'),
           'audiotest.au')
        missing = []
        eq(self._au.get_param('attachment', header='content-disposition'), '')
        self.assertIs(self._au.get_param('foo', failobj=missing,
                                         header='content-disposition'),
                      missing)
        # Try some missing stuff
        self.assertIs(self._au.get_param('foobar', missing), missing)
        self.assertIs(self._au.get_param('attachment', missing,
                                         header='foobar'), missing)



# Test the basic MIMEImage class 
Example #20
Source File: 4_generate_email.py    From deep-learning-note with MIT License 6 votes vote down vote up
def attach_images(*fns):
    email = MIMEMultipart()
    for fn in fns:
        if not img_patt.search(fn.split('.')[-1]):
            # Following is kinda like throwing an exception, but better.
            print("%s doesn't seem to be an image file. Skipping." % fn)
            continue
        if url_patt.match(fn):
            data = requests.get(fn).content
        else:
            with open(fn, 'rb') as f:
                data = f.read()
        img = MIMEImage(data, name=fn)
        img.add_header('Content-Disposition', 'attachment; filename="%s"' % fn)
        email.attach(img)
    return email 
Example #21
Source File: test_email_renamed.py    From datafari with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        fp = openfile('PyBanner048.gif')
        try:
            self._imgdata = fp.read()
        finally:
            fp.close()
        self._im = MIMEImage(self._imgdata) 
Example #22
Source File: BaseTestClasses.py    From email2pdf with MIT License 5 votes vote down vote up
def attachImage(self, content_id=None, jpeg=True, content_type=None, content_type_add_filename=False, inline=False, force_filename=False, extension=None):
        if jpeg:
            real_filename = self.JPG_FILENAME
            file_suffix = 'jpg' if extension is None else extension
        else:
            real_filename = self.PNG_FILENAME
            file_suffix = 'png' if extension is None else extension

        if file_suffix != '':
            suffix = "." + file_suffix
        else:
            suffix = file_suffix

        with tempfile.NamedTemporaryFile(prefix="email2pdf_unittest_image", suffix=suffix) as temp_file:
            _, basic_file_name = os.path.split(temp_file.name)

        with open(real_filename, 'rb') as image_file:
            image = MIMEImage(image_file.read())
            if content_id:
                image.add_header('Content-ID', content_id)

            if content_type:
                self._replace_header(image, 'Content-Type', content_type)

            if content_type_add_filename:
                image.set_param('name', basic_file_name, header='Content-Type')

            if inline:
                if force_filename:
                    self._replace_header(image, 'Content-Disposition', 'inline; filename="%s"' % basic_file_name)
                else:
                    self._replace_header(image, 'Content-Disposition', 'inline')
            else:
                self._replace_header(image, 'Content-Disposition', 'attachment; filename="%s"' % basic_file_name)
            self.msg.attach(image)

        if inline and not force_filename:
            return None
        else:
            return basic_file_name 
Example #23
Source File: mailers.py    From django-htk with MIT License 5 votes vote down vote up
def attach_images_to_message(message, images):
    for image in images:
      fp = open(image, 'rb')
      filename = os.path.basename(image)
      msg_image = MIMEImage(fp.read())
      fp.close()
      msg_image.add_header('Content-ID', '<%s>' % filename)
      message.attach(msg_image) 
Example #24
Source File: test_mail.py    From django-sendgrid-v5 with MIT License 5 votes vote down vote up
def test_mime(self):
        msg = EmailMultiAlternatives(
            subject="Hello, World!",
            body=" ",
            from_email="Sam Smith <sam.smith@example.com>",
            to=["John Doe <john.doe@example.com>", "jane.doe@example.com"],
        )

        content = '<body><img src="cid:linux_penguin" /></body>'
        msg.attach_alternative(content, "text/html")
        with open("test/linux-penguin.png", "rb") as f:
            img = MIMEImage(f.read())
            img.add_header("Content-ID", "<linux_penguin>")
            msg.attach(img)

        result = self.backend._build_sg_mail(msg)
        self.assertEqual(len(result["content"]), 2)
        self.assertDictEqual(result["content"][0], {"type": "text/plain", "value": " "})
        self.assertDictEqual(result["content"][1], {"type": "text/html", "value": content})
        self.assertEqual(len(result["attachments"]), 1)
        self.assertEqual(result["attachments"][0]["content_id"], "linux_penguin")

        with open("test/linux-penguin.png", "rb") as f:
            if sys.version_info >= (3.0, 0.0, ):
                self.assertEqual(bytearray(result["attachments"][0]["content"], "utf-8"), base64.b64encode(f.read()))
            else:
                self.assertEqual(result["attachments"][0]["content"], base64.b64encode(f.read()))
        self.assertEqual(result["attachments"][0]["type"], "image/png") 
Example #25
Source File: Smail.py    From Smail with GNU General Public License v3.0 5 votes vote down vote up
def add_attachment(self,filepath,filename=None):
        if filename == None:
            filename=os.path.basename(filepath)

        with open(filepath,'rb') as f:
            file=f.read()

        ctype, encoding = mimetypes.guess_type(filepath)
        if ctype is None or encoding is not None:ctype = "application/octet-stream"
        maintype, subtype = ctype.split('/', 1)

        if maintype == "text":
            with open(filepath) as f:file=f.read()
            attachment = MIMEText(file, _subtype=subtype)
        elif maintype == "image":
            with open(filepath,'rb') as f:file=f.read()
            attachment = MIMEImage(file, _subtype=subtype)
        elif maintype == "audio":
                with open(filepath,'rb') as f:file=f.read()
                attachment = MIMEAudio(file, _subtype=subtype)
        else:
                with open(filepath,'rb') as f:file=f.read()
                attachment = MIMEBase(maintype,subtype)
                attachment.set_payload(file)
                attachment.add_header('Content-Disposition', 'attachment', filename=filename)
                encoders.encode_base64(attachment)

        attachment.add_header('Content-Disposition', 'attachment', filename=filename)
        attachment.add_header('Content-ID',str(self.attachment_num))
        self.attachment_num+=1

        self.attachment_list.append(attachment) 
Example #26
Source File: email_lean.py    From notes with Apache License 2.0 5 votes vote down vote up
def send_file_email():
    # 设置好文件内容
    message = MIMEMultipart()
    message['From'] = from_sender
    message['To'] = to_address
    message['Subject'] = "this is title"

    # 添加html形式的文本内容
    with open("test_html.html", 'r') as f:
        html_content = f.read()
        html = MIMEText(str(html_content), 'html', 'utf-8')
    message.attach(html)

    with open('/Users/ruiqi/Downloads/默认文件1584974964625.png', 'rb') as h:
        image = MIMEImage(h.read())
        image['Content-Type'] = 'application/octest-stream'
        image['Content-Disposition'] = 'attachment;filename="1.png"'
        # image.add_header('Content-ID', '<image1>')
        message.attach(image)

    with open('/Users/ruiqi/Downloads/默认文件1584974964625.png', 'rb') as h:
        image = MIMEImage(h.read())
        image['Content-Type'] = 'application/octest-stream'
        image['Content-Disposition'] = 'attachment;filename="1.png"'
        image.add_header('Content-ID', '<image1>')
        message.attach(image)

    server = smtplib.SMTP_SSL(smtp_server, smtp_port)
    server.login(from_sender, password)
    server.sendmail(from_sender, to_address, message.as_string())
    server.quit()
    print("发送完毕") 
Example #27
Source File: test_email_renamed.py    From datafari with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        fp = openfile('PyBanner048.gif')
        try:
            data = fp.read()
        finally:
            fp.close()

        container = MIMEBase('multipart', 'mixed', boundary='BOUNDARY')
        image = MIMEImage(data, name='dingusfish.gif')
        image.add_header('content-disposition', 'attachment',
                         filename='dingusfish.gif')
        intro = MIMEText('''\
Hi there,

This is the dingus fish.
''')
        container.attach(intro)
        container.attach(image)
        container['From'] = 'Barry <barry@digicool.com>'
        container['To'] = 'Dingus Lovers <cravindogs@cravindogs.com>'
        container['Subject'] = 'Here is your dingus fish'

        now = 987809702.54848599
        timetuple = time.localtime(now)
        if timetuple[-1] == 0:
            tzsecs = time.timezone
        else:
            tzsecs = time.altzone
        if tzsecs > 0:
            sign = '-'
        else:
            sign = '+'
        tzoffset = ' %s%04d' % (sign, tzsecs // 36)
        container['Date'] = time.strftime(
            '%a, %d %b %Y %H:%M:%S',
            time.localtime(now)) + tzoffset
        self._msg = container
        self._im = image
        self._txt = intro 
Example #28
Source File: 15_6_send_email_from_gmail.py    From Python-Network-Programming with MIT License 5 votes vote down vote up
def send_email(sender, recipient):
    """ Send email message """
    msg = MIMEMultipart()
    msg['Subject'] = 'Python Emaill Test'
    msg['To'] = recipient
    msg['From'] = sender
    subject = 'Python email Test'
    message = 'Images attached.'
    # attach imgae files
    files = os.listdir(os.getcwd())
    gifsearch = re.compile(".gif", re.IGNORECASE)
    files = filter(gifsearch.search, files)
    for filename in files:
        path = os.path.join(os.getcwd(), filename)
        if not os.path.isfile(path):
            continue
        img = MIMEImage(open(path, 'rb').read(), _subtype="gif")
        img.add_header('Content-Disposition', 'attachment', filename=filename)
        msg.attach(img)
 
    part = MIMEText('text', "plain")
    part.set_payload(message)
    msg.attach(part)
    
    # create smtp session
    session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
    session.ehlo()
    session.starttls()
    session.ehlo
    password = getpass.getpass(prompt="Enter your Google password: ") 
    session.login(sender, password)
    session.sendmail(sender, recipient, msg.as_string())
    print ("Email sent.")
    session.quit() 
Example #29
Source File: notify.py    From HomeAssistantConfig with MIT License 5 votes vote down vote up
def _build_multipart_msg(message, images):
    """Build Multipart message with in-line images."""
    _LOGGER.debug("Building multipart email with embedded attachment(s)")
    msg = MIMEMultipart('related')
    msg_alt = MIMEMultipart('alternative')
    msg.attach(msg_alt)
    body_txt = MIMEText(message)
    msg_alt.attach(body_txt)
    body_text = ['<p>{}</p><br>'.format(message)]

    for atch_num, atch_name in enumerate(images):
        cid = 'image{}'.format(atch_num)
        body_text.append('<img src="cid:{}"><br>'.format(cid))
        try:
            with open(atch_name, 'rb') as attachment_file:
                file_bytes = attachment_file.read()
                try:
                    attachment = MIMEImage(file_bytes)
                    msg.attach(attachment)
                    attachment.add_header('Content-ID', '<{}>'.format(cid))
                except TypeError:
                    _LOGGER.warning("Attachment %s has an unknown MIME type. "
                                    "Falling back to file", atch_name)
                    attachment = MIMEApplication(file_bytes, Name=atch_name)
                    attachment['Content-Disposition'] = ('attachment; '
                                                         'filename="%s"' %
                                                         atch_name)
                    msg.attach(attachment)
        except FileNotFoundError:
            _LOGGER.warning("Attachment %s not found. Skipping", atch_name)

    body_html = MIMEText(''.join(body_text), 'html')
    msg_alt.attach(body_html)
    return msg 
Example #30
Source File: test_email_renamed.py    From datafari with Apache License 2.0 5 votes vote down vote up
def test_checkSetMinor(self):
        im = MIMEImage(self._imgdata, 'fish')
        self.assertEqual(im.get_content_type(), 'image/fish')