Python email.mime.multipart.MIMEMultipart() Examples
The following are 30 code examples for showing how to use email.mime.multipart.MIMEMultipart(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.
You may also want to check out all available functions/classes of the module
email.mime.multipart
, or try the search function
.
Example 1
Project: deep-learning-note Author: wdxtub File: 4_generate_email.py License: MIT License | 6 votes |
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 2
Project: dataiku-contrib Author: dataiku File: recipe.py License: Apache License 2.0 | 6 votes |
def send_email(contact): recipient = contact[recipient_column] email_text = body_value if use_body_value else contact.get(body_column, "") email_subject = subject_value if use_subject_value else contact.get(subject_column, "") sender = sender_value if use_sender_value else contact.get(sender_column, "") msg = MIMEMultipart() msg["From"] = sender msg["To"] = recipient msg["Subject"]= email_subject # Leave some space for proper displaying of the attachment msg.attach(MIMEText(email_text + '\n\n', 'plain', body_encoding)) for a in mime_parts: msg.attach(a) s.sendmail(sender, [recipient], msg.as_string())
Example 3
Project: QBotWebWrap Author: zeruniverse File: qqbot.py License: GNU General Public License v3.0 | 6 votes |
def sendfailmail(): try: SUBJECT = 'QQ点赞机下线提醒' TO = [sendtomail] msg = MIMEMultipart('alternative') msg['Subject'] = Header(SUBJECT, 'utf-8') msg['From'] = mailsig+'<'+mailuser+'>' msg['To'] = ', '.join(TO) part = MIMEText("Fatal error occured. Please go to the website and login again!", 'plain', 'utf-8') msg.attach(part) server = smtplib.SMTP(mailserver, 25) server.login(mailuser, mailpass) server.login(mailuser, mailpass) server.sendmail(mailuser, TO, msg.as_string()) server.quit() return True except Exception , e: logging.error("发送程序错误邮件失败:"+str(e)) return False
Example 4
Project: QBotWebWrap Author: zeruniverse File: qqbot.py License: GNU General Public License v3.0 | 6 votes |
def sendfailmail(): global QQUserName, MyUIN try: SUBJECT = 'QQ挂机下线提醒: '+str(QQUserName)+'[QQ号:'+str(MyUIN)+']' TO = [sendtomail] msg = MIMEMultipart('alternative') msg['Subject'] = Header(SUBJECT, 'utf-8') msg['From'] = mailsig+'<'+mailuser+'>' msg['To'] = ', '.join(TO) part = MIMEText("Fatal error occured. Please restart the program and login again!", 'plain', 'utf-8') msg.attach(part) server = smtplib.SMTP(mailserver, 25) server.login(mailuser, mailpass) server.login(mailuser, mailpass) server.sendmail(mailuser, TO, msg.as_string()) server.quit() return True except Exception , e: logging.error("发送程序错误邮件失败:"+str(e)) return False
Example 5
Project: QBotWebWrap Author: zeruniverse File: qqbot.py License: GNU General Public License v3.0 | 6 votes |
def smtpmail(self,subinfo): try: SUBJECT = '来自 '+subinfo+'的留言' TO = [sendtomail] msg = MIMEMultipart('alternative') msg['Subject'] = Header(SUBJECT, 'utf-8') msg['From'] = mailsig+'<'+mailuser+'>' msg['To'] = ', '.join(TO) part = MIMEText(self.content, 'plain', 'utf-8') msg.attach(part) server = smtplib.SMTP(mailserver, 25) server.login(mailuser, mailpass) server.login(mailuser, mailpass) server.sendmail(mailuser, TO, msg.as_string()) server.quit() return True except Exception, e: logging.error("error sending msg:"+str(e)) return False
Example 6
Project: QBotWebWrap Author: zeruniverse File: qqbot.py License: GNU General Public License v3.0 | 6 votes |
def smtpmail(self,SUBJECT): try: TO = [sendtomail] msg = MIMEMultipart('alternative') msg['Subject'] = Header(SUBJECT, 'utf-8') msg['From'] = mailsig+'<'+mailuser+'>' msg['To'] = ', '.join(TO) part = MIMEText(self.content, 'plain', 'utf-8') msg.attach(part) server = smtplib.SMTP(mailserver, 25) server.login(mailuser, mailpass) server.login(mailuser, mailpass) server.sendmail(mailuser, TO, msg.as_string()) server.quit() return True except Exception, e: logging.error("error sending msg:"+str(e)) return False
Example 7
Project: QBotWebWrap Author: zeruniverse File: qqbot.py License: GNU General Public License v3.0 | 6 votes |
def sendfailmail(): try: SUBJECT = 'QQ小黄鸡下线提醒' TO = [sendtomail] msg = MIMEMultipart('alternative') msg['Subject'] = Header(SUBJECT, 'utf-8') msg['From'] = mailsig+'<'+mailuser+'>' msg['To'] = ', '.join(TO) part = MIMEText("Fatal error occured. Please go to the website and login again!", 'plain', 'utf-8') msg.attach(part) server = smtplib.SMTP(mailserver, 25) server.login(mailuser, mailpass) server.login(mailuser, mailpass) server.sendmail(mailuser, TO, msg.as_string()) server.quit() return True except Exception , e: logging.error("发送程序错误邮件失败:"+str(e)) return False
Example 8
Project: Stockeye Author: anfederico File: watch.py License: MIT License | 6 votes |
def sendEmail(subject, body, credentials): self = credentials[0] password = credentials[1] fromAddr = credentials[2] toAddr = credentials[3] msg = MIMEMultipart() msg['From'] = fromAddr msg['To'] = toAddr msg['Subject'] = subject msgText = MIMEText(body, 'html', 'UTF-8') msg.attach(msgText) server = SMTP('smtp.gmail.com', 587) server.starttls() server.login(self, password) text = msg.as_string() server.sendmail(fromAddr, toAddr, text) server.quit() # --- Scraping Methods ---------------------------------------------------------
Example 9
Project: messages Author: trp07 File: test_email.py License: MIT License | 6 votes |
def test_generate_email(get_email, mocker): """ GIVEN a valid Email object WHEN Email.generate_email() is called THEN assert the email structure is created """ header_mock = mocker.patch.object(Email, '_add_header') body_mock = mocker.patch.object(Email, '_add_body') attach_mock = mocker.patch.object(Email, '_add_attachments') e = get_email e._generate_email() assert isinstance(e.message, MIMEMultipart) assert header_mock.call_count == 1 assert body_mock.call_count == 1 assert attach_mock.call_count == 1 ############################################################################## # TESTS: Email._add_header ##############################################################################
Example 10
Project: messages Author: trp07 File: test_email.py License: MIT License | 6 votes |
def test_add_body(get_email, mocker): """ GIVEN a valid Email object, where Email.generate_email() has been called WHEN Email.add_body() is called THEN assert body_text is attached """ attach_mock = mocker.patch.object(Email, '_add_attachments') header_mock = mocker.patch.object(Email, '_add_header') mime_attach_mock = mocker.patch.object(MIMEMultipart, 'attach') e = get_email e._generate_email() assert mime_attach_mock.call_count == 1 ############################################################################## # TESTS: Email._add_attachments ##############################################################################
Example 11
Project: messages Author: trp07 File: test_email.py License: MIT License | 6 votes |
def test_add_attachments_str_travis(get_email, mocker): """ GIVEN a valid Email object, where Email.generate_email() has been called and Email.attachments is a str WHEN Email.add_attachments() is called THEN assert correct attachments are attached """ header_mock = mocker.patch.object(Email, '_add_header') body_mock = mocker.patch.object(Email, '_add_body') mime_attach_mock = mocker.patch.object(MIMEMultipart, 'attach') e = get_email PATH = '/home/travis/build/trp07/messages/tests/data/' e.attachments = PATH + 'file1.txt' e._generate_email() assert mime_attach_mock.call_count == 1 ############################################################################## # TESTS: Email._get_session ##############################################################################
Example 12
Project: zvt Author: zvtvz File: informer.py License: MIT License | 6 votes |
def send_message(self, to_user, title, body, **kwargs): if self.ssl: smtp_client = smtplib.SMTP_SSL() else: smtp_client = smtplib.SMTP() smtp_client.connect(zvt_env['smtp_host'], zvt_env['smtp_port']) smtp_client.login(zvt_env['email_username'], zvt_env['email_password']) msg = MIMEMultipart('alternative') msg['Subject'] = Header(title).encode() msg['From'] = "{} <{}>".format(Header('zvt').encode(), zvt_env['email_username']) if type(to_user) is list: msg['To'] = ", ".join(to_user) else: msg['To'] = to_user msg['Message-id'] = email.utils.make_msgid() msg['Date'] = email.utils.formatdate() plain_text = MIMEText(body, _subtype='plain', _charset='UTF-8') msg.attach(plain_text) try: smtp_client.sendmail(zvt_env['email_username'], to_user, msg.as_string()) except Exception as e: self.logger.exception('send email failed', e)
Example 13
Project: bitmask-dev Author: leapcode File: test_incoming_mail.py License: GNU General Public License v3.0 | 6 votes |
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 14
Project: bitmask-dev Author: leapcode File: test_incoming_mail.py License: GNU General Public License v3.0 | 6 votes |
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 15
Project: bitmask-dev Author: leapcode File: test_incoming_mail.py License: GNU General Public License v3.0 | 6 votes |
def testExtractAttachedKeyAndNotOpenPGPHeader(self): KEY = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n..." KEYURL = "https://leap.se/key.txt" OpenPGP = "id=12345678; url=\"%s\"; preference=signencrypt" % (KEYURL,) message = MIMEMultipart() message.add_header("from", ADDRESS_2) message.add_header("OpenPGP", OpenPGP) key = MIMEApplication("", "pgp-keys") key.set_payload(KEY) message.attach(key) self.fetcher._keymanager.put_raw_key = Mock( return_value=defer.succeed(None)) self.fetcher._keymanager.fetch_key = Mock() def put_raw_key_called(_): self.fetcher._keymanager.put_raw_key.assert_called_once_with( KEY, address=ADDRESS_2) self.assertFalse(self.fetcher._keymanager.fetch_key.called) d = self._do_fetch(message.as_string()) d.addCallback(put_raw_key_called) return d
Example 16
Project: bitmask-dev Author: leapcode File: test_incoming_mail.py License: GNU General Public License v3.0 | 6 votes |
def testExtractOpenPGPHeaderIfInvalidAttachedKey(self): KEY = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n..." KEYURL = "https://leap.se/key.txt" OpenPGP = "id=12345678; url=\"%s\"; preference=signencrypt" % (KEYURL,) message = MIMEMultipart() message.add_header("from", ADDRESS_2) message.add_header("OpenPGP", OpenPGP) key = MIMEApplication("", "pgp-keys") key.set_payload(KEY) message.attach(key) self.fetcher._keymanager.put_raw_key = Mock( return_value=defer.fail(KeyAddressMismatch())) self.fetcher._keymanager.fetch_key = Mock() def put_raw_key_called(_): self.fetcher._keymanager.put_raw_key.assert_called_once_with( KEY, address=ADDRESS_2) self.fetcher._keymanager.fetch_key.assert_called_once_with( ADDRESS_2, KEYURL) d = self._do_fetch(message.as_string()) d.addCallback(put_raw_key_called) return d
Example 17
Project: ironpython2 Author: IronLanguages File: test_email_renamed.py License: Apache License 2.0 | 6 votes |
def test_mime_attachments_in_constructor(self): eq = self.assertEqual text1 = MIMEText('') text2 = MIMEText('') msg = MIMEMultipart(_subparts=(text1, text2)) eq(len(msg.get_payload()), 2) eq(msg.get_payload(0), text1) eq(msg.get_payload(1), text2) # A general test of parser->model->generator idempotency. IOW, read a message # in, parse it into a message object tree, then without touching the tree, # regenerate the plain text. The original text and the transformed text # should be identical. Note: that we ignore the Unix-From since that may # contain a changed date.
Example 18
Project: ironpython2 Author: IronLanguages File: test_email_renamed.py License: Apache License 2.0 | 6 votes |
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 19
Project: shutit Author: ianmiell File: emailer.py License: MIT License | 6 votes |
def __compose(self): """ Compose the message, pulling together body, attachments etc """ msg = MIMEMultipart() msg['Subject'] = self.config['shutit.core.alerting.emailer.subject'] msg['To'] = self.config['shutit.core.alerting.emailer.mailto'] msg['From'] = self.config['shutit.core.alerting.emailer.mailfrom'] # add the module's maintainer as a CC if configured if self.config['shutit.core.alerting.emailer.mailto_maintainer']: msg['Cc'] = self.config['shutit.core.alerting.emailer.maintainer'] if self.config['shutit.core.alerting.emailer.signature'] != '': signature = '\n\n' + self.config['shutit.core.alerting.emailer.signature'] else: signature = self.config['shutit.core.alerting.emailer.signature'] body = MIMEText('\n'.join(self.lines) + signature) msg.attach(body) for attach in self.attaches: msg.attach(attach) return msg
Example 20
Project: thenextquant Author: SimoHaiLiu File: sendmail.py License: MIT License | 6 votes |
def send(self): """ 发送邮件 """ message = MIMEMultipart('related') message['Subject'] = self._subject message['From'] = self._username message['To'] = ",".join(self._to_emails) message['Date'] = email.utils.formatdate() message.preamble = 'This is a multi-part message in MIME format.' ma = MIMEMultipart('alternative') mt = MIMEText(self._content, 'plain', 'GB2312') ma.attach(mt) message.attach(ma) smtp = aiosmtplib.SMTP(hostname=self._host, port=self._port, timeout=self._timeout, use_tls=self._tls) await smtp.connect() await smtp.login(self._username, self._password) await smtp.send_message(message) logger.info('send email success! FROM:', self._username, 'TO:', self._to_emails, 'CONTENT:', self._content, caller=self)
Example 21
Project: BinderFilter Author: dxwu File: test_email_renamed.py License: MIT License | 6 votes |
def test_mime_attachments_in_constructor(self): eq = self.assertEqual text1 = MIMEText('') text2 = MIMEText('') msg = MIMEMultipart(_subparts=(text1, text2)) eq(len(msg.get_payload()), 2) eq(msg.get_payload(0), text1) eq(msg.get_payload(1), text2) # A general test of parser->model->generator idempotency. IOW, read a message # in, parse it into a message object tree, then without touching the tree, # regenerate the plain text. The original text and the transformed text # should be identical. Note: that we ignore the Unix-From since that may # contain a changed date.
Example 22
Project: BinderFilter Author: dxwu File: test_email_renamed.py License: MIT License | 6 votes |
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 23
Project: oss-ftp Author: aliyun File: test_email_renamed.py License: MIT License | 6 votes |
def test_mime_attachments_in_constructor(self): eq = self.assertEqual text1 = MIMEText('') text2 = MIMEText('') msg = MIMEMultipart(_subparts=(text1, text2)) eq(len(msg.get_payload()), 2) eq(msg.get_payload(0), text1) eq(msg.get_payload(1), text2) # A general test of parser->model->generator idempotency. IOW, read a message # in, parse it into a message object tree, then without touching the tree, # regenerate the plain text. The original text and the transformed text # should be identical. Note: that we ignore the Unix-From since that may # contain a changed date.
Example 24
Project: oss-ftp Author: aliyun File: test_email_renamed.py License: MIT License | 6 votes |
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 25
Project: spidermon Author: scrapinghub File: __init__.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
def get_message(self): subject = self.get_subject() body_text = self.get_body_text() body_html = self.get_body_html() message = MIMEMultipart("alternative") message.set_charset("UTF-8") message["Subject"] = subject message["From"] = self.sender message["To"] = ", ".join(self.to) if self.cc: message["Cc"] = ", ".join(self.cc) if self.bcc: message["Bcc"] = ", ".join(self.bcc) if self.reply_to: message["reply-to"] = self.reply_to message.attach(MIMEText(body_text, "plain")) if body_html: message.attach(MIMEText(body_html, "html")) return message
Example 26
Project: QQParking Author: zeruniverse File: QQBot.py License: GNU General Public License v3.0 | 6 votes |
def sendfailmail(): global QQUserName, MyUIN try: SUBJECT = 'QQ挂机下线提醒: '+str(QQUserName)+'[QQ号:'+str(MyUIN)+']' TO = [sendtomail] msg = MIMEMultipart('alternative') msg['Subject'] = Header(SUBJECT, 'utf-8') msg['From'] = mailsig+'<'+mailuser+'>' msg['To'] = ', '.join(TO) part = MIMEText("Fatal error occured. Please restart the program and login again!", 'plain', 'utf-8') msg.attach(part) server = smtplib.SMTP(mailserver, 25) server.login(mailuser, mailpass) server.login(mailuser, mailpass) server.sendmail(mailuser, TO, msg.as_string()) server.quit() return True except Exception , e: logging.error("发送程序错误邮件失败:"+str(e)) return False
Example 27
Project: QQParking Author: zeruniverse File: QQBot.py License: GNU General Public License v3.0 | 6 votes |
def smtpmail(self,subinfo): try: SUBJECT = '来自 '+subinfo+'的留言' TO = [sendtomail] msg = MIMEMultipart('alternative') msg['Subject'] = Header(SUBJECT, 'utf-8') msg['From'] = mailsig+'<'+mailuser+'>' msg['To'] = ', '.join(TO) part = MIMEText(self.content, 'plain', 'utf-8') msg.attach(part) server = smtplib.SMTP(mailserver, 25) server.login(mailuser, mailpass) server.login(mailuser, mailpass) server.sendmail(mailuser, TO, msg.as_string()) server.quit() return True except Exception, e: logging.error("error sending msg:"+str(e)) return False
Example 28
Project: QQParking Author: zeruniverse File: QQBot.py License: GNU General Public License v3.0 | 6 votes |
def smtpmail(self,SUBJECT): try: TO = [sendtomail] msg = MIMEMultipart('alternative') msg['Subject'] = Header(SUBJECT, 'utf-8') msg['From'] = mailsig+'<'+mailuser+'>' msg['To'] = ', '.join(TO) part = MIMEText(self.content, 'plain', 'utf-8') msg.attach(part) server = smtplib.SMTP(mailserver, 25) server.login(mailuser, mailpass) server.login(mailuser, mailpass) server.sendmail(mailuser, TO, msg.as_string()) server.quit() return True except Exception, e: logging.error("error sending msg:"+str(e)) return False
Example 29
Project: streamalert Author: airbnb File: aws.py License: Apache License 2.0 | 6 votes |
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 30
Project: streamalert Author: airbnb File: aws.py License: Apache License 2.0 | 6 votes |
def _construct_body(msg, body): """ Create the body of the email Args: msg (MIMEMultipart): Email Object to contruct body body (str): the body is represented as a string body (dict): dictionary of message_type/message for the body (for use with HTML) """ if isinstance(body, str): # For use with string based body LOGGER.debug("body is a string of: %s", body) msg.attach(MIMEText(body)) elif isinstance(body, dict): # For use with HTML body LOGGER.debug("body is not a string, attaching body of: %s", body) textual_message = MIMEMultipart("alternative") for m_type, message in body.items(): part = MIMEText(message, m_type) textual_message.attach(part) msg.attach(textual_message) return msg