Python email.mime.text.MIMEText() Examples
The following are 30
code examples of email.mime.text.MIMEText().
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.text
, or try the search function
.
Example #1
Source File: informer.py From zvt with MIT License | 15 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 #2
Source File: util.py From openSUSE-release-tools with GNU General Public License v2.0 | 11 votes |
def mail_send_with_details(relay, sender, subject, to, text, xmailer=None, followup_to=None, dry=True): import smtplib from email.mime.text import MIMEText import email.utils msg = MIMEText(text, _charset='UTF-8') msg['Subject'] = subject msg['Message-ID'] = email.utils.make_msgid() msg['Date'] = email.utils.formatdate(localtime=1) msg['From'] = sender msg['To'] = to if followup_to: msg['Mail-Followup-To'] = followup_to if xmailer: msg.add_header('X-Mailer', xmailer) msg.add_header('Precedence', 'bulk') if dry: logger.debug(msg.as_string()) return logger.info("%s: %s", msg['To'], msg['Subject']) s = smtplib.SMTP(relay) s.sendmail(msg['From'], {msg['To'], sender }, msg.as_string()) s.quit()
Example #3
Source File: qqbot.py From QBotWebWrap with GNU General Public License v3.0 | 10 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 #4
Source File: test_soledad_adaptor.py From bitmask-dev with GNU General Public License v3.0 | 9 votes |
def test_get_msg_from_string_multipart(self): msg = MIMEMultipart() msg['Subject'] = 'Test multipart mail' msg.attach(MIMEText(u'a utf8 message', _charset='utf-8')) adaptor = self.get_adaptor() msg = adaptor.get_msg_from_string(MessageClass, msg.as_string()) self.assertEqual( 'base64', msg.wrapper.cdocs[1].content_transfer_encoding) self.assertEqual( 'text/plain', msg.wrapper.cdocs[1].content_type) self.assertEqual( 'utf-8', msg.wrapper.cdocs[1].charset) self.assertEqual( 'YSB1dGY4IG1lc3NhZ2U=\n', msg.wrapper.cdocs[1].raw)
Example #5
Source File: recipe.py From dataiku-contrib with Apache License 2.0 | 8 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 #6
Source File: test_email_renamed.py From ironpython2 with Apache License 2.0 | 8 votes |
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 #7
Source File: test_email_renamed.py From ironpython2 with Apache License 2.0 | 8 votes |
def test_one_part_in_a_multipart(self): eq = self.ndiffAssertEqual outer = MIMEBase('multipart', 'mixed') outer['Subject'] = 'A subject' outer['To'] = 'aperson@dom.ain' outer['From'] = 'bperson@dom.ain' outer.set_boundary('BOUNDARY') msg = MIMEText('hello world') outer.attach(msg) eq(outer.as_string(), '''\ Content-Type: multipart/mixed; boundary="BOUNDARY" MIME-Version: 1.0 Subject: A subject To: aperson@dom.ain From: bperson@dom.ain --BOUNDARY Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit hello world --BOUNDARY-- ''')
Example #8
Source File: utils.py From ffplayout-engine with GNU General Public License v3.0 | 8 votes |
def send_mail(self, msg): if _mail.recip: # write message to temp file for rate limit with open(self.temp_msg, 'w+') as f: f.write(msg) self.current_time() message = MIMEMultipart() message['From'] = _mail.s_addr message['To'] = _mail.recip message['Subject'] = _mail.subject message['Date'] = formatdate(localtime=True) message.attach(MIMEText('{} {}'.format(self.time, msg), 'plain')) text = message.as_string() try: server = smtplib.SMTP(_mail.server, _mail.port) except socket.error as err: playout_logger.error(err) server = None if server is not None: server.starttls() try: login = server.login(_mail.s_addr, _mail.s_pass) except smtplib.SMTPAuthenticationError as serr: playout_logger.error(serr) login = None if login is not None: server.sendmail(_mail.s_addr, _mail.recip, text) server.quit()
Example #9
Source File: utils.py From GerbLook with BSD 2-Clause "Simplified" License | 7 votes |
def send_email(msg_to, msg_subject, msg_body, msg_from=None, smtp_server='localhost', envelope_from=None, headers={}): if not msg_from: msg_from = app.config['EMAIL_FROM'] if not envelope_from: envelope_from = parseaddr(msg_from)[1] msg = MIMEText(msg_body) msg['Subject'] = Header(msg_subject) msg['From'] = msg_from msg['To'] = msg_to msg['Date'] = formatdate() msg['Message-ID'] = make_msgid() msg['Errors-To'] = envelope_from if request: msg['X-Submission-IP'] = request.remote_addr s = smtplib.SMTP(smtp_server) s.sendmail(envelope_from, msg_to, msg.as_string()) s.close()
Example #10
Source File: envia_relatorio_por_email.py From ir with Mozilla Public License 2.0 | 7 votes |
def envia_relatorio_html_por_email(assunto, relatorio_html): gmail_user = os.environ['GMAIL_FROM'] gmail_password = os.environ['GMAIL_PASSWORD'] to = os.environ['SEND_TO'].split(sep=';') msg = MIMEText(relatorio_html, 'html') msg['Subject'] = assunto msg['From'] = gmail_user try: server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.ehlo() server.login(gmail_user, gmail_password) for to_addrs in to: msg['To'] = to_addrs server.send_message(msg, from_addr=gmail_user, to_addrs=to_addrs) print('Email enviado com sucesso') return True except Exception as ex: print('Erro ao enviar email') print(ex) return False
Example #11
Source File: watch.py From Stockeye with MIT License | 7 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 #12
Source File: send_email_with_python.py From autopython with GNU General Public License v3.0 | 7 votes |
def send_mail(to_email,message): # 定义邮件发送 # Define send_mail() function smtp_host = 'smtp.xxx.com' # 发件箱服务器 # Outbox Server from_email = 'from_email@xxx.com' # 发件邮箱 # from_email passwd = 'xxxxxx' # 发件邮箱密码 # from_email_password msg = MIMEText(message,'plain','utf-8') msg['Subject'] = Header(u'Email Subject','utf-8').encode() # 邮件主题 # Email Subject smtp_server = smtplib.SMTP(smtp_host,25) # 发件服务器端口 # Outbox Server Port smtp_server.login(from_email,passwd) smtp_server.sendmail(from_email,[to_email],msg.as_string()) smtp_server.quit()
Example #13
Source File: users.py From cascade-server with Apache License 2.0 | 7 votes |
def send_reset_email(self): expires = datetime.datetime.now() + reset_password_timeout url = self.generate_reset_link() body = ("A password reset for {} has been requested.\r\n".format(self.username), "Navigate to {} to complete reset.".format(url), "Expires on {}".format(expires.isoformat()) ) message = MIMEText('\r\n'.join(body)) message['Subject'] = "Password Reset Link for CASCADE on {}".format(settings.load()['server']['hostname']) message['From'] = 'cascade@' + settings.load()['server']['hostname'] message['To'] = self.email server = smtplib.SMTP(settings.load()['links']['smtp']) server.set_debuglevel(1) server.sendmail(message['From'], [self.email], message.as_string()) server.quit()
Example #14
Source File: qqbot.py From QBotWebWrap with GNU General Public License v3.0 | 7 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 #15
Source File: util.py From openSUSE-release-tools with GNU General Public License v2.0 | 7 votes |
def mail_send_with_details(relay, sender, subject, to, text, xmailer=None, followup_to=None, dry=True): import smtplib from email.mime.text import MIMEText import email.utils msg = MIMEText(text, _charset='UTF-8') msg['Subject'] = subject msg['Message-ID'] = email.utils.make_msgid() msg['Date'] = email.utils.formatdate(localtime=1) msg['From'] = sender msg['To'] = to if followup_to: msg['Mail-Followup-To'] = followup_to if xmailer: msg.add_header('X-Mailer', xmailer) msg.add_header('Precedence', 'bulk') if dry: logger.debug(msg.as_string()) return logger.info("%s: %s", msg['To'], msg['Subject']) s = smtplib.SMTP(relay) s.sendmail(msg['From'], {msg['To'], sender }, msg.as_string()) s.quit()
Example #16
Source File: qqbot.py From QBotWebWrap with GNU General Public License v3.0 | 7 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 #17
Source File: qqbot.py From QBotWebWrap with GNU General Public License v3.0 | 7 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 #18
Source File: test_email_renamed.py From ironpython2 with 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 #19
Source File: test_email_renamed.py From ironpython2 with Apache License 2.0 | 6 votes |
def test_epilogue(self): eq = self.ndiffAssertEqual fp = openfile('msg_21.txt') try: text = fp.read() finally: fp.close() msg = Message() msg['From'] = 'aperson@dom.ain' msg['To'] = 'bperson@dom.ain' msg['Subject'] = 'Test' msg.preamble = 'MIME message' msg.epilogue = 'End of MIME message\n' msg1 = MIMEText('One') msg2 = MIMEText('Two') msg.add_header('Content-Type', 'multipart/mixed', boundary='BOUNDARY') msg.attach(msg1) msg.attach(msg2) sfp = StringIO() g = Generator(sfp) g.flatten(msg) eq(sfp.getvalue(), text)
Example #20
Source File: smtp_twitter_send_mail.py From python-hacker with Apache License 2.0 | 6 votes |
def send_mail(user, pwd, to, subject, text, smtp_address, smtp_port): msg = MIMEText(text) msg['From'] = user msg['To'] = to msg['Subject'] = subject try: smtpServer = smtplib.SMTP(smtp_address, smtp_port) print '[+] Connecting To Mail Server.' smtpServer.ehlo() print '[+] Starting Encrypted Session.' smtpServer.starttls() smtpServer.ehlo() print '[+] Logging Into Mail Server.' smtpServer.login(user, pwd) print '[+] Sending Mail.' smtpServer.sendmail(user, to, msg.as_string()) smtpServer.close() print '[+] Mail Sent Successfully.' except: print '[-] Sending Mail Failed.'
Example #21
Source File: test_email_renamed.py From ironpython2 with Apache License 2.0 | 6 votes |
def test_seq_parts_in_a_multipart_with_none_epilogue(self): eq = self.ndiffAssertEqual outer = MIMEBase('multipart', 'mixed') outer['Subject'] = 'A subject' outer['To'] = 'aperson@dom.ain' outer['From'] = 'bperson@dom.ain' outer.epilogue = None msg = MIMEText('hello world') outer.attach(msg) outer.set_boundary('BOUNDARY') eq(outer.as_string(), '''\ Content-Type: multipart/mixed; boundary="BOUNDARY" MIME-Version: 1.0 Subject: A subject To: aperson@dom.ain From: bperson@dom.ain --BOUNDARY Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit hello world --BOUNDARY-- ''')
Example #22
Source File: test_email_renamed.py From ironpython2 with Apache License 2.0 | 6 votes |
def test_seq_parts_in_a_multipart_with_none_preamble(self): eq = self.ndiffAssertEqual outer = MIMEBase('multipart', 'mixed') outer['Subject'] = 'A subject' outer['To'] = 'aperson@dom.ain' outer['From'] = 'bperson@dom.ain' outer.preamble = None msg = MIMEText('hello world') outer.attach(msg) outer.set_boundary('BOUNDARY') eq(outer.as_string(), '''\ Content-Type: multipart/mixed; boundary="BOUNDARY" MIME-Version: 1.0 Subject: A subject To: aperson@dom.ain From: bperson@dom.ain --BOUNDARY Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit hello world --BOUNDARY-- ''')
Example #23
Source File: test_email_renamed.py From ironpython2 with Apache License 2.0 | 6 votes |
def test_seq_parts_in_a_multipart_with_empty_epilogue(self): eq = self.ndiffAssertEqual outer = MIMEBase('multipart', 'mixed') outer['Subject'] = 'A subject' outer['To'] = 'aperson@dom.ain' outer['From'] = 'bperson@dom.ain' outer.epilogue = '' msg = MIMEText('hello world') outer.attach(msg) outer.set_boundary('BOUNDARY') eq(outer.as_string(), '''\ Content-Type: multipart/mixed; boundary="BOUNDARY" MIME-Version: 1.0 Subject: A subject To: aperson@dom.ain From: bperson@dom.ain --BOUNDARY Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit hello world --BOUNDARY-- ''')
Example #24
Source File: emailer.py From shutit with 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 #25
Source File: __init__.py From py-mysql-elasticsearch-sync with MIT License | 6 votes |
def _send_email(self, title, content): """ send notification email """ if not self.config.get('email'): return import smtplib from email.mime.text import MIMEText msg = MIMEText(content) msg['Subject'] = title msg['From'] = self.config['email']['from']['username'] msg['To'] = ', '.join(self.config['email']['to']) # Send the message via our own SMTP server. s = smtplib.SMTP() s.connect(self.config['email']['from']['host']) s.login(user=self.config['email']['from']['username'], password=self.config['email']['from']['password']) s.sendmail(msg['From'], msg['To'], msg=msg.as_string()) s.quit()
Example #26
Source File: __init__.py From py-mysql-elasticsearch-sync with MIT License | 6 votes |
def _send_email(self, title, content): """ send notification email """ if not self.config.get('email'): return import smtplib from email.mime.text import MIMEText msg = MIMEText(content) msg['Subject'] = title msg['From'] = self.config['email']['from']['username'] msg['To'] = ', '.join(self.config['email']['to']) # Send the message via our own SMTP server. s = smtplib.SMTP() s.connect(self.config['email']['from']['host']) s.login(user=self.config['email']['from']['username'], password=self.config['email']['from']['password']) s.sendmail(msg['From'], msg['To'], msg=msg.as_string()) s.quit()
Example #27
Source File: sendmail.py From thenextquant with 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 #28
Source File: smtplib_send_email.py From python-hacker with Apache License 2.0 | 6 votes |
def sendMail(user, pwd, to, subject, text, smtp_address, smtp_port): msg = MIMEText(text) msg['From'] = user msg['To'] = to msg['Subject'] = subject try: smtpServer = smtplib.SMTP(smtp_address, smtp_port) print '[+] Connecting To EMail Server.' smtpServer.ehlo() print '[+] Starting Encrypted Session.' smtpServer.starttls() smtpServer.ehlo() print '[+] Logging Into Mail Server.' smtpServer.login(user, pwd) print '[+] Sending Mail.' smtpServer.sendmail(user, to, msg.as_string()) smtpServer.close() print '[+] Mail Sent Successfully.' except Exception, e: print '[+] Sending Mail Failed.' print e
Example #29
Source File: test_email_renamed.py From ironpython2 with 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 #30
Source File: test_email_renamed.py From ironpython2 with Apache License 2.0 | 6 votes |
def test_header_splitter(self): eq = self.ndiffAssertEqual msg = MIMEText('') # It'd be great if we could use add_header() here, but that doesn't # guarantee an order of the parameters. msg['X-Foobar-Spoink-Defrobnit'] = ( 'wasnipoop; giraffes="very-long-necked-animals"; ' 'spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"') sfp = StringIO() g = Generator(sfp) g.flatten(msg) eq(sfp.getvalue(), '''\ Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Foobar-Spoink-Defrobnit: wasnipoop; giraffes="very-long-necked-animals"; spooge="yummy"; hippos="gargantuan"; marshmallows="gooey" ''')