我们从Python开源项目中,提取了以下28个代码示例,用于说明如何使用email.MIMEText.MIMEText()。
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"; \tspooge="yummy"; hippos="gargantuan"; marshmallows="gooey" ''')
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 MIMEText class
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.
def send_email_account(remote_server, remote_port, username, password, email_from, email_to, subject, body): if (remote_server == "smtp.gmail.com"): send_email_gmail(username, password, email_from, email_to, subject, body) else: # connect to remote mail server and forward message on server = smtplib.SMTP(remote_server, remote_port) msg = MIMEMultipart() msg['From'] = email_from msg['To'] = email_to msg['Subject'] = subject msg.attach(MIMEText(body, 'plain')) smtp_sendmail_return = "" try: server.login(username, password) smtp_sendmail_return = server.sendmail(email_from, email_to, msg.as_string()) except Exception, e: print 'SMTP Exception:\n' + str( e) + '\n' + str( smtp_sendmail_return) finally: server.quit()
def send_email_direct(email_from, email_to, subject, body): # find the appropiate mail server domain = email_to.split('@')[1] remote_server = get_mx_record(domain) if (remote_server is None): print "No valid email server could be found for [%s]!" % (email_to) return # connect to remote mail server and forward message on server = smtplib.SMTP(remote_server, 25) msg = MIMEMultipart() msg['From'] = email_from msg['To'] = email_to msg['Subject'] = subject msg.attach(MIMEText(body, 'plain')) smtp_sendmail_return = "" try: smtp_sendmail_return = server.sendmail(email_from, email_to, msg.as_string()) except Exception, e: print 'SMTP Exception:\n' + str( e) + '\n' + str( smtp_sendmail_return) finally: server.quit()
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" ''')
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 MIMEText class
def test__all__(self): module = __import__('email') 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', ])
def sendmail(toaddr, subject, body): """ ??????? :param SMTPSession session: ??????????? :param str fromaddr: ??? :param list toaddr: ????? :param str subject: ???? :param str body: ???? :rtype: dict: ???????????? """ session = SMTPSession fromaddr = ALERT_EMAIL_FROM msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = ', '.join(toaddr) msg['Subject'] = subject msg.attach(MIMEText(body, 'plain')) text = msg.as_string() yield session.send(fromaddr, toaddr, text) # ???????????????? # send_alert_mail = partial(sendmail, session=SMTPSession, # fromaddr=ALERT_EMAIL_FROM)
def _send_mail(self, args): if args is None: raise RuntimeError("Passed argument for send mail is not set!") if len(args) != 2: raise RuntimeError("Passed argument for send mail has invalid number of arguments!") subject = args[0] text = args[1] msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = self.mail_sender msg['To'] = ', '.join(self.mail_receiver_list) msg.attach(MIMEText(text)) msg_string = msg.as_string() logging.debug(msg_string) smtp_conn = smtplib.SMTP(self.mail_server) smtp_conn.sendmail(self.mail_sender, self.mail_receiver_list, msg_string) smtp_conn.quit()
def sender(username, password, toaddress, email_text): fromaddr = username toaddrs = toaddress now = datetime.datetime.now() msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddrs msg['Subject'] = "Tv shows [ " + now.strftime('%Y/%m/%d') + " ]" msg.attach(MIMEText(email_text, 'plain')) text = msg.as_string() # Credentials (if needed) username = username password = password # The actual mail send server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(username, password) server.sendmail(fromaddr, toaddrs, text) server.quit()
def sendEmailPrintable(textToSend,fileToSend,addressToSend, pathToFile, subject): msg = MIMEMultipart() msg['From'] = printableFromAddress msg['To'] = addressToSend msg['Subject'] = subject msg.attach(MIMEText(textToSend,'plain')) attachment = open(pathToFile+fileToSend, "rb") part = MIMEBase('application','octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % fileToSend) msg.attach(part) server = smtplib.SMTP(emailServer, 25) #server.starttls() text = msg.as_string() server.sendmail(printableFromAddress, addressToSend.split(","), text) server.quit attachment.close()
def send_mail(server, from_address, from_name, to_address, subject, body_arg, return_addr, tls): msg = MIMEMultipart('alternative') msg['To'] = to_address msg['Date'] = formatdate(localtime = True) msg['Subject'] = subject msg.add_header('reply-to', return_addr) msg.add_header('from', from_name + "<" + from_address + ">") part1 = MIMEText(body_arg, 'plain') part2 = MIMEText(body_arg, 'html') msg.attach(part1) msg.attach(part2) try: smtp = smtplib.SMTP(server) smtp.set_debuglevel(VERBOSE) smtp.sendmail(from_address, to_address, msg.as_string()) smtp.quit() except smtplib.SMTPException: print FAIL + "[-] Error: unable to send email to ", to_address, ENDC # --------------------- PARSE includes/config.massmail -------------------
def notify(self, event): try: msg = MIMEMultipart() msg['From'] = self.emailer_settings['from_address'] msg['To'] = self.emailer_settings['to_address'] msg['Subject'] = "{0} {1}".format(event['subject'], event['scanname']) targets = "".join(["<li>{0}</li>".format(t) for t in event['targets']]) if event['targets'] else "" html = str(self.emailer_settings['email_template']).format(event['server'], event['scanname'], event['scanid'], event['subject'], targets) msg.attach(MIMEText(html, 'html')) mail_server = smtplib.SMTP(self.emailer_settings['smtp_host'], self.emailer_settings['smtp_port']) mail_server.sendmail(msg['From'], msg['To'], msg.as_string()) mail_server.quit() except (Exception, AttributeError) as e: # we don't want email failure to stop us, just log that it happened Logger.app.error("Your emailer settings in config.ini is incorrectly configured. Error: {}".format(e))
def cloudscan_notify(self, recipient, subject, git_url, ssc_url, state, scan_id, scan_name): try: msg = MIMEMultipart() msg['From'] = self.from_address msg['To'] = recipient msg['Subject'] = subject html = str(self.email_template).format(git_url, ssc_url, scan_name, scan_id, state, self.chatroom) msg.attach(MIMEText(html, 'html')) mail_server = smtplib.SMTP(self.smtp_host, self.smtp_port) mail_server.sendmail(msg['From'], msg['To'], msg.as_string()) mail_server.quit() except (Exception, AttributeError) as e: # we don't want email failure to stop us, just log that it happened Logger.app.error("Your emailer settings in config.ini is incorrectly configured. Error: {}".format(e))