我们从Python开源项目中,提取了以下47个代码示例,用于说明如何使用email.MIMEMultipart.MIMEMultipart()。
def as_mailobj(self): # Create the root message and fill in the from, to, and subject headers msgRoot = MIMEMultipart('related') msgRoot['Subject'] = self.subject msgRoot['From'] = self.get_sender() msgRoot['To'] = ", ".join(self.recipients) msgRoot.preamble = 'Generated by mailprod python tool' for i in range(len(self.headers)): name, value, params = self.headers[i] msgRoot.add_header(name, value, **params) for i in range(len(self.body)): part = self.body[i] msgRoot.attach(part) for i in range(len(self.attachments)): attachment = self.attachments[i] msgRoot.attach(attachment) return msgRoot
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__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 send(To, Subject, Body, Cc=[], Bcc=[], html=False, files=[]): """Send an email """ subtype = 'html' if html else 'plain' message = MIMEMultipart() message['To'] = ', '.join(To) message['Subject'] = Subject message['Cc'] = ', '.join(Cc) message['Bcc'] = ', '.join(Bcc) message.attach(MIMEText(Body, subtype)) for f in files: with open(f, "rb") as In: part = MIMEApplication(In.read(), Name=basename(f)) part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f) message.attach(part) message = {'raw': base64.urlsafe_b64encode(message.as_string())} credentials = oauth2client.file.Storage(CREDENTIALS_PATH).get() Http = credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1', http=Http) message = service.users().messages().send(userId='me', body=message).execute()
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 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)
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 sendmail(to_list,subject,content): # translation me = mail_user+"<"+mail_user+"@"+mail_postfix+">" msg = MIMEMultipart('related') msg['Subject'] = email.Header.Header(subject,'utf-8') msg['From'] = me msg['To'] = ";".join(to_list) msg.preamble = 'This is a multi-part message in MIME format.' msgAlternative = MIMEMultipart('alternative') msgText = MIMEText(content, 'plain', 'utf-8') msgAlternative.attach(msgText) msg.attach(msgAlternative) try: s = smtplib.SMTP() s.connect(mail_host) s.login(mail_user,mail_pwd) s.sendmail(me, to_list, msg.as_string()) s.quit() except Exception,e: print e return False return True
def sendhtmlmail(to_list,subject,content): # translation me = mail_user+"<"+mail_user+"@"+mail_postfix+">" msg = MIMEMultipart('related') msg['Subject'] = email.Header.Header(subject,'utf-8') msg['From'] = me msg['To'] = ";".join(to_list) msg.preamble = 'This is a multi-part message in MIME format.' msgAlternative = MIMEMultipart('alternative') msgText = MIMEText(content, 'html', 'utf-8') msgAlternative.attach(msgText) msg.attach(msgAlternative) try: s = smtplib.SMTP() s.connect(mail_host) s.login(mail_user,mail_pwd) s.sendmail(me, to_list, msg.as_string()) s.quit() except Exception,e: print e return False return True
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))
def send_mail_reinit(destination_address, token): source_address = info_mail.mail body = "Rendez-vous à cette adresse pour réinitialiser votre mot de passe - localhost:5000/changer-mot-de-passe/" + token subject = "Récupération du mot de passe CMS TP2" msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = source_address msg['To'] = destination_address msg.attach(MIMEText(body, 'plain')) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(source_address, info_mail.mdp) text = msg.as_string() server.sendmail(source_address, destination_address, text) server.quit()
def send_mail_invite(destination_address, token): source_address = info_mail.mail body = "Rendez-vous à cette adresse pour vous inscrire en tant qu'admin sur CMS TP2 - localhost:5000/inscription/" + token subject = "Invitation au rôle d'admin CMS TP2" msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = source_address msg['To'] = destination_address msg.attach(MIMEText(body, 'plain')) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(source_address, info_mail.mdp) text = msg.as_string() server.sendmail(source_address, destination_address, text) server.quit()
def send_mail( server, subject, sender, receiver, text, filepath ): msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = sender msg['To'] = ', '.join( receiver ) msg.attach( MIMEText( text ) ) filename = os.path.split( filepath )[1] filetype = filename.split( '.' )[1] img = MIMEImage( file( filepath ).read(), _subtype=filetype ) img.add_header( 'Content-Disposition', "attachment; filename= %s" % filename ) msg.attach( img ) mail_server = smtplib.SMTP( server ) mail_server.sendmail( sender, receiver, msg.as_string() ) mail_server.quit()
def send_mail(report_contents): msg = MIMEMultipart() msg['Subject'] = SUBJECT msg['From'] = EMAIL_FROM msg['To'] = ', '.join(EMAIL_TO) fp = open('/home/pierre/es_email_intel/wordcloud.png', 'rb') try: msgImage = MIMEImage(fp.read()) except: fp = open('/home/pierre/es_email_intel/1x1.png', 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<wordcloud>') msg.attach(msgImage) part = MIMEBase('application', "octet-stream") part.set_payload(report_contents) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="report.html"') msg.attach(part) server = smtplib.SMTP(EMAIL_SERVER) server.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
def __init__(self, to, efrom, subject, text, attach, user, pw, server, port, callback=None): self.msg = MIMEMultipart() self.text = text self.attach = attach self.to = to self.efrom = efrom self.callbackfunction=callback self.gmail_user = user self.gmail_pwd = pw self.server=server self.port=port self.msg['From'] = self.efrom self.msg['To'] = self.to self.msg['Subject'] = subject print "SENDMAIL: Sending started." thread=threading.Thread.__init__(self) return thread
def process(options, args): config = get_config(options) # Write the email msg = MIMEMultipart() msg['From'] = config['fromaddr'] msg['To'] = config['toaddrs'] msg['Subject'] = options.subject body = options.body msg.attach(MIMEText(body, 'plain')) # Attach image if options.image_file: try: filename = open(options.image_file, "rb") attach_image = MIMEImage(filename.read()) attach_image.add_header('Content-Disposition', 'attachment; filename = %s'%options.image_file) msg.attach(attach_image) filename.close() except: msg.attach(MIMEText('Image attachment error', 'plain')) # Converting email to text text = msg.as_string() # The actual mail send server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo() server.starttls() server.ehlo() server.login(config['username'],config['password']) server.sendmail(config['fromaddr'], config['toaddrs'], text) server.quit()
def send_email(image_path,ssocr_output): msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = "[TEST IMAGE] %s - %s %s" %(machine_number,hall,machine_type) body = "My IP %s \n SSOCR output is %s \n\n\n\n\n\n\n" %(get_ip.get_ip(),ssocr_output) msg.attach(MIMEText(body, 'plain')) filename = "test_image.jpg" attachment = open(image_path, "rb") part = MIMEBase('application', 'octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % filename) msg.attach(part) tries = 0 while True: if (tries > 60): exit() try: server = smtplib.SMTP('smtp.gmail.com', 587) break except Exception as e: tries = tries + 1 time.sleep(1) server.starttls() server.login(fromaddr, "I_am_a_laundry") text = msg.as_string() server.sendmail(fromaddr, toaddr, text) print('Send Email Successfully') server.quit()
def send_email_direct(email_to, email_from, display_name, subject, body, attach_fname, attach_filepath, debug=False): # 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 # make sure we have a display name if (not display_name): display_name = email_from # connect to remote mail server and forward message on server = smtplib.SMTP(remote_server, 25) msg = MIMEMultipart() msg['From'] = display_name msg['To'] = email_to msg['Subject'] = subject msg.attach(MIMEText(body, 'plain')) if (attach_fname): attachment = open(attach_filepath, "rb") part = MIMEBase('application', 'octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % attach_fname) msg.attach(part) smtp_sendmail_return = "" if debug: server.set_debuglevel(True) try: smtp_sendmail_return = server.sendmail(email_from, email_to, msg.as_string()) except Exception, e: exception = 'SMTP Exception:\n' + str( e) + '\n' + str( smtp_sendmail_return) finally: server.quit()
def send_email_account(remote_server, remote_port, username, password, email_to, email_from, display_name, subject, body, attach_fname, attach_filepath, debug=False): if (remote_server == "smtp.gmail.com"): send_email_gmail(username, password, email_to, email_from, subject, body, debug) else: # make sure we have a display name if (not display_name): display_name = email_from # connect to remote mail server and forward message on server = smtplib.SMTP(remote_server, remote_port) msg = MIMEMultipart() msg['From'] = display_name msg['To'] = email_to msg['Subject'] = subject msg.attach(MIMEText(body, 'plain')) if (attach_fname): attachment = open(attach_filepath, "rb") part = MIMEBase('application', 'octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % attach_fname) msg.attach(part) smtp_sendmail_return = "" if debug: server.set_debuglevel(True) try: server.login(username, password) smtp_sendmail_return = server.sendmail(email_from, email_to, msg.as_string()) except Exception, e: exception = 'SMTP Exception:\n' + str( e) + '\n' + str( smtp_sendmail_return) finally: server.quit()
def sendMail(gmailUser,gmailPassword,recipient,subject,text): msg = MIMEMultipart() msg['From'] = gmailUser msg['To'] = recipient msg['Subject'] = subject msg.attach(MIMEText(text)) mailServer = smtplib.SMTP('smtp.gmail.com', 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(gmailUser, gmailPassword) mailServer.sendmail(gmailUser, recipient, msg.as_string()) mailServer.close() print('[-] Sent email to %s :' % recipient)
def __init__(self, user, passwd, smtp,port,usettls=False): self.mailUser = user self.mailPassword = passwd self.smtpServer = smtp self.smtpPort = port if usettls: smtp_class = smtplib.SMTP_SSL else: smtp_class = smtplib.SMTP self.mailServer = smtp_class(self.smtpServer, self.smtpPort) self.mailServer.ehlo() self.mailServer.login(self.mailUser, self.mailPassword) self.msg = MIMEMultipart() #????????mailserver
def reinitMailInfo(): self.msg = MIMEMultipart() #????????????????????????html??plain????????????
def test_make_boundary(self): msg = MIMEMultipart('form-data') # Note that when the boundary gets created is an implementation # detail and might change. self.assertEqual(msg.items()[0][1], 'multipart/form-data') # Trigger creation of boundary msg.as_string() self.assertEqual(msg.items()[0][1][:33], 'multipart/form-data; boundary="==') # XXX: there ought to be tests of the uniqueness of the boundary, too.
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)
def test_default_multipart_constructor(self): msg = MIMEMultipart() self.assertTrue(msg.is_multipart()) # 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 sendEmail(SUBJECT, BODY, ATTACH_LIST, TO, FROM, SENDER, PASSWORD, SMTP_SERVER, SMTP_PORT): """Sends an email.""" txt = MIMEText(BODY.encode('utf-8'), 'html', 'utf-8') msg = MIMEMultipart() msg.attach(txt) _logger = logging.getLogger(__name__) for attach in ATTACH_LIST: try: att = MIMEText(open(attach, 'rb').read(), 'base64', 'utf-8') filename = os.path.basename(attach) att["Content-Type"] = 'application/octet-stream' att["Content-Disposition"] = 'attachment; filename="%s"' % filename msg.attach(att) except Exception: _logger.error(u'?? %s ?????' % attach) continue msg['From'] = SENDER msg['To'] = TO msg['Subject'] = SUBJECT try: session = smtplib.SMTP() session.connect(SMTP_SERVER, SMTP_PORT) session.starttls() session.login(FROM, PASSWORD) session.sendmail(SENDER, TO, msg.as_string()) session.close() return True except Exception, e: _logger.error(e) return False
def notify(id_, email, cmd): print('[%s] Sending report %s to %s' % (datetime.datetime.now(), id_, email)) msg = MIMEMultipart() msg['From'] = SMTP_USER msg['To'] = email msg['Subject'] = "Your scan results are ready" body = "{2}\n\nView online:\n{0}/static/results/{1}.html\n\nDownload:\n{0}/static/results/{1}.nmap\n{0}/static/results/{1}.xml\n{0}/static/results/{1}.gnmap".format(BASE_URL, id_, cmd) msg.attach(MIMEText(body, 'plain')) server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT) server.ehlo() server.starttls() server.ehlo() server.login(SMTP_USER, SMTP_PASS) text = msg.as_string() server.sendmail(SMTP_USER, email, text)