def sendEmail(self, authInfo, fromAdd, toAdd, subject, htmlText=None, files=None): strFrom = fromAdd strTo = toAdd server = authInfo.get('server') user = authInfo.get('user') passwd = authInfo.get('password') if not (server and user and passwd): print 'incomplete login info, exit now' return msgRoot = MIMEMultipart('related') msgRoot['Subject'] = subject msgRoot['From'] = strFrom msgRoot['To'] = ",".join(strTo) msgRoot.preamble = 'This is a multi-part message in MIME format.' # Encapsulate the plain and HTML versions of the message body in an # 'alternative' part, so message agents can decide which they want to display. msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) #msgText = MIMEText(plainText, 'plain', 'utf-8') #msgAlternative.attach(msgText) msgText = MIMEText(htmlText, 'html', 'utf-8') msgAlternative.attach(msgText) if files != None: for file in files: if ".png" in file: att = MIMEImage(open(file, 'rb').read()) att.add_header('Content-ID', '00000001') # att["Content-Type"] = 'application/octet-stream' # att["Content-Disposition"] = 'attachment; filename="' + os.path.basename(file)+ '"' msgRoot.attach(att) else: att = MIMEText(open(file, 'rb').read(), 'base64', 'utf-8') att["Content-Type"] = 'application/octet-stream' att["Content-Disposition"] = 'attachment; filename="' + os.path.basename( file) + '"' msgRoot.attach(att) smtp = smtplib.SMTP() smtp.set_debuglevel(0) smtp.connect(server) smtp.login(user, passwd) result = smtp.sendmail(strFrom, toAdd, msgRoot.as_string()) print result #smtp.sendmail() smtp.quit()
def _create_msg(): msg = MIMEMultipart("related") msg["Subject"] = "Zabbix Screen Report: %s" % screen_name msg["From"] = me msg["To"] = ";".join(to_list) msg.preamble = "This is a multi-part message in MIME format." contents = "<h1>Screen %s</h1><br>" % screen_name contents += "<table>" for g_name in graphs: with open(os.path.join(GRAPH_PATH, g_name), "rb") as fp: msg_image = MIMEImage(fp.read()) msg_image.add_header("Content-ID", "<%s>" % g_name) msg.attach(msg_image) contents += "" contents += "<tr><td><img src='cid:%s'></td></tr>" % g_name contents += "</table>" msg_text = MIMEText(contents, "html") msg_alternative = MIMEMultipart("alternative") msg_alternative.attach(msg_text) msg.attach(msg_alternative) return msg
def sendEmail(): """ Send out an email (if necessary) """ # Set-up the chart email msgRoot = MIMEMultipart('related') msgRoot['Subject'] = subject msgRoot['From'] = email_from msgRoot['To'] = COMMASPACE.join(email_to) msgRoot.preamble = 'This is a multi-part message in MIME format.' # Encapsulate the plain and HTML versions of the message body in an # 'alternative' part, so message agents can decide which they want to display. msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgText = MIMEText(body) msgAlternative.attach(msgText) # We reference the image in the IMG SRC attribute by the ID we give it below msgText = MIMEText(body_html, 'html') msgAlternative.attach(msgText) # This example assumes the image is in the current directory msgImage = MIMEImage(chart_image) # Define the image's ID as referenced above msgImage.add_header('Content-ID', '<image1>') msgRoot.attach(msgImage) s = smtplib.SMTP('localhost') s.sendmail(email_from, email_to, msgRoot.as_string()) s.quit()
def emailFile(to, subject, message, filePath, mimeType=None, fromEmail=FROMEMAIL, server=SERVER): """ sends an email attachment to the given address or list of addesses. if the mimeType is not specified, it uses mimetypes.guess_type to determine it. """ toList, to = processTo(to) msg = MIMEMultipart() msg['Subject'] = subject msg['To'] = to msg['From'] = fromEmail msg['Date'] = formatdate() msg.preamble = 'You are not using a MIME-aware reader\n' msg.epilogue = '' #add the main message msg.attach(MIMEText(message)) if type(filePath) is list: for f in filePath: addFile(f, msg, mimeType) else: addFile(filePath, msg, mimeType) rawEmail(toList, msg.as_string(), server=server, fromEmail=fromEmail)
def SendEmail(authInfo, fromAdd, toAdd, subject, htmlText): strFrom = fromAdd strTo = toAdd server = authInfo.get('server') user = authInfo.get('user') passwd = authInfo.get('password') if not (server and user and passwd) : print 'incomplete login info, exit now' return # 设定root信息 msgRoot = MIMEMultipart('related') msgRoot['Subject'] = subject msgRoot['From'] = strFrom msgRoot['To'] = strTo msgRoot.preamble = 'This is a multi-part message in MIME format.' msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgText = MIMEText(htmlText, 'html', 'utf-8') msgAlternative.attach(msgText) #发送邮件 smtp = smtplib.SMTP() #设定调试级别,依情况而定 # smtp.set_debuglevel(1) smtp.connect(server) smtp.login(user, passwd) smtp.sendmail(strFrom, strTo, msgRoot.as_string()) smtp.quit()
def sendmail(from_addr, to_addr_list, subject, message, login, password): # Create the root message and fill in the from, to, and subject headers msgRoot = MIMEMultipart('related') msgRoot['From'] = from_addr msgRoot['Subject'] = subject msgRoot['To'] = str(to_addr_list) msgRoot.preamble = 'This is a multi-part message in MIME format.' # Encapsulate the plain and HTML versions of the message body in an # 'alternative' part, so message agents can decide which they want to display. msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgText = MIMEText('This is the alternative plain text message.') msgAlternative.attach(msgText) # We reference the image in the IMG SRC attribute by the ID we give it below msgText = MIMEText(message, 'html') msgAlternative.attach(msgText) # Send the email (this example assumes SMTP authentication is required) server = smtplib.SMTP( 'smtp.gmail.com:587' ) # This would work for Gmail, could be any SMTP server server.starttls() server.login(login, password) server.sendmail(from_addr, to_addr_list, msgRoot.as_string()) server.quit()
def sendEmail(): grab_cam = subprocess.Popen(“sudo fswebcam - p YUYV image1.jpeg”, shell = True) grab_cam.wait() image_path = ‘image1.jpeg’ username = “cemakdemir99 @ gmail.com” # gönderilen mail hesabın adını yazıyoruz password = “#######” # gönderilen mail hesabın şifresini yazıyoruz COMMASPACE = ‘, ’ message = MIMEMultipart() message[‘Subject’] = ‘Hareket Algilandi’ me = ‘####### @ gmail.com’ # gönderilecek mail hesabın adını yazıyoruz receivers = ‘########@ gmail.com’ # gönderilecek mail hesabın adını yazıyoruz message[‘From’] = me message[‘To’] = COMMASPACE.join(receivers) message.preamble = ‘Hareket’ fp = open(‘image1.jpeg’, ‘rb’) img = MIMEImage(fp.read()) fp.close() message.attach(img) try: server = smtplib.SMTP(“smtp.gmail.com”, 587) # portu mail servis saglayacisi server.ehlo() server.starttls() server.login(username, password) server.sendmail(me, receivers.split(“, ”), message.as_string()) server.close() print ‘mail gonderildi’ except: print “mail gonderilemedi”
def create_msg(subject, sender, recipient, html, text, images): msgRoot = MIMEMultipart('related') msgRoot['Subject'] = subject msgRoot['From'] = named(sender) msgRoot['To'] = named(recipient) msgRoot.preamble = 'This is a multi-part message from %s.' % str( settings.APP_SHORT_NAME) msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgAlternative.attach(MIMEText(text, _charset='utf-8')) msgAlternative.attach(MIMEText(html, 'html', _charset='utf-8')) for img in images: try: fp = open(img[0], 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<' + img[1] + '>') msgRoot.attach(msgImage) except: pass return msgRoot.as_string()
def my_send_mail(subject, txt, sender, to=[], files=[], charset='UTF-8'): from email import Encoders from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText for dest in to: dest = dest.strip() msg = MIMEMultipart('related') msg['Subject'] = subject msg['From'] = sender msg['To'] = dest msg.preamble = 'This is a multi-part message in MIME format.' msgAlternative = MIMEMultipart('alternative') msg.attach(msgAlternative) msgAlternative.attach(MIMEText(txt, _charset=charset)) msgAlternative.attach(MIMEText(txt, 'html', _charset=charset)) for f in files: part = MIMEBase('application', "octet-stream") part.set_payload( open(f,"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) from smtplib import SMTP smtp = SMTP() try: smtp.connect(host=settings.EMAIL_HOST) smtp.sendmail(sender,dest, msg.as_string()) smtp.quit() return smtp except Exception as e: return e
def create_email(self, first_name, last_name, target_email, uid): msg = MIMEMultipart() msg['Subject'] = self.config['mailer.subject'] if self.config.get('mailer.reply_to_email'): msg.add_header('reply-to', self.config['mailer.reply_to_email']) if self.config.get('mailer.source_email_alias'): msg['From'] = "\"{0}\" <{1}>".format(self.config['mailer.source_email_alias'], self.config['mailer.source_email']) else: msg['From'] = self.config['mailer.source_email'] msg['To'] = target_email importance = self.config.get('mailer.importance', 'Normal') if importance != 'Normal': msg['Importance'] = importance sensitivity = self.config.get('mailer.sensitivity', 'Normal') if sensitivity != 'Normal': msg['Sensitivity'] = sensitivity msg.preamble = 'This is a multi-part message in MIME format.' msg_alt = MIMEMultipart('alternative') msg.attach(msg_alt) msg_template = open(self.config['mailer.html_file'], 'r').read() formatted_msg = format_message(msg_template, self.config, first_name=first_name, last_name=last_name, uid=uid, target_email=target_email) msg_body = MIMEText(formatted_msg, "html") msg_alt.attach(msg_body) if self.config.get('mailer.attachment_file'): attachment = self.config['mailer.attachment_file'] attachfile = MIMEBase(*mimetypes.guess_type(attachment)) attachfile.set_payload(open(attachment, 'rb').read()) Encoders.encode_base64(attachfile) attachfile.add_header('Content-Disposition', "attachment; filename=\"{0}\"".format(os.path.basename(attachment))) msg.attach(attachfile) return msg
def sendEmail(fromAdd, toAdd, subject, plainText): strFrom = fromAdd strTo =toAdd # 设定root信息 msgRoot = MIMEMultipart('related') msgRoot['Subject'] = subject msgRoot['From'] = strFrom msgRoot['To'] = ','.join(toAdd) #与原文不同 msgRoot.preamble = 'This is a multi-part message in MIME format.' # Encapsulate the plain and HTML versions of the message body in an # 'alternative' part, so message agents can decide which they want to display. msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) #设定纯文本信息 msgText = MIMEText(plainText, 'plain', 'utf-8') msgAlternative.attach(msgText) #发送邮件 smtp = smtplib.SMTP() #设定调试级别,依情况而定 smtp.set_debuglevel(1) smtp.connect(EMAIL_HOST) smtp.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD) smtp.sendmail(strFrom, strTo, msgRoot.as_string()) smtp.quit()
def send_email_csv_attach(toaddrs, mail, csv_fn, fromaddr=EMAIL_SENDER_ADDR): msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddrs msg['Subject'] = 'please check attached csv file for cr status' msg.preamble = 'You will not see this in a MIME-aware mail reader.\n' # To guarantee the message ends with a newline msg.epilogue = '' #body text = MIMEText(mail) msg.attach(text) #attachment csv = MIMEBase('text', 'x-comma-separated-values') fp = open(csv_fn, 'rb') csv.set_payload(fp.read()) Encoders.encode_base64(csv) csv.add_header('Content-Disposition', 'attachment', filename=os.path.basename(csv_fn)) msg.attach(csv) server = smtplib.SMTP('remotesmtp.mot.com') server.set_debuglevel(1) server.sendmail(fromaddr, toaddrs, msg.as_string()) server.quit()
def send_email(address, message): """Send an email to the address saying that prepration for the dir is done""" import smtplib from email.MIMEText import MIMEText from email.MIMEMultipart import MIMEMultipart from email.MIMENonMultipart import MIMENonMultipart from email.MIMEBase import MIMEBase from email import Encoders import mimetypes # # Prepare the message # text = message text_mes = MIMEText(text) message = MIMEMultipart() message.preamble = 'pKD message' message.epilogue = '' message['Subject'] = 'Message from pKD server' message['From'] = 'pKD Server <*****@*****.**>' message['Reply-To'] = '*****@*****.**' message['To'] = address message.attach(text_mes) # # Send the email # #sys.stdout=X try: server = smtplib.SMTP('193.1.169.34') #mail.ucd.ie server.set_debuglevel(1) server.login('jensniel', 'alpha2') server.sendmail('*****@*****.**', address, message.as_string()) server.quit() except: pass return
def mail(user, to, subject, text, html, *attachments): pswd = getpass.getpass("pass: "******"related") msg["From"] = user msg["To"] = to msg["Subject"] = subject msg.preamble = "This is a multi-part message in MIME format." alt = MIMEMultipart("alternative") msg.attach(alt) msgtext = MIMEText(text) alt.attach(msgtext) msgtext = MIMEText(html, "html") alt.attach(msgtext) for path in attachments: msg.attach(make_attach(path)) mailServer = smtplib.SMTP("smtp.gmail.com", 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() login = False while not login: try: mailServer.login(user, pswd) login = True except smtplib.SMTPAuthenticationError, e: print "password rejected", user, pswd, e pswd = getpass.getpass("pass: ")
def sendEmail(name, pictureString): import smtplib from email.MIMEImage import MIMEImage from email.MIMEMultipart import MIMEMultipart COMMASPACE = ', ' SMTP_SERVER = 'smtp.gmail.com' SMTP_PORT = 587 msg = MIMEMultipart() msg['Subject'] = 'The name of the burglar is ' + name + "." msg['From'] = '*****@*****.**' msg['To'] = COMMASPACE.join('*****@*****.**') msg.preamble = 'The name of the burglar is ' # + str(name) + "." fp = open(pictureString, 'rb') img = MIMEImage(fp.read()) fp.close() msg.attach(img) s = smtplib.SMTP(SMTP_SERVER, SMTP_PORT) s.ehlo() s.starttls() s.ehlo() s.login('*****@*****.**', '$anFi3rro') s.sendmail('*****@*****.**', '*****@*****.**', msg.as_string()) s.quit() return
def test_mail(request): msg = MIMEMultipart() msg['Subject'] = 'Test Multipart from tanglab' msg['From'] = '*****@*****.**' msg['To'] = '[email protected],[email protected]' msg.preamble = 'This is a test message again' fromaddr = "*****@*****.**" toaddrs = ['*****@*****.**', '*****@*****.**'] content = MIMEText("Dear Tanglab User: Attached are the AMPL and SBML files we generated for you. -- Tanglab") msg.attach(content) fp = open('/research-www/engineering/tanglab/flux/temp/rak1.ampl', 'rb') ampl = MIMEText(fp.read()) ampl.add_header('Content-Disposition', 'attachment; filename="rak1.ampl"') fp.close() msg.attach(ampl) fp = open('/research-www/engineering/tanglab/flux/temp/ilo1.sbml', 'rb') sbml = MIMEText(fp.read()) sbml.add_header('Content-Disposition', 'attachment; filename="ilo1.sbml"') fp.close() msg.attach(sbml) server = smtplib.SMTP('localhost') server.sendmail(fromaddr, toaddrs, msg.as_string()) server.quit() return HttpResponse(content = " Even New Email sent. ", status = 200, content_type = "text/html")
def sendmail(to_list,sub,con): """发送邮件 """ # 设置服务器名称、用户名、密码以及邮件后缀 mail_host="smtp.139.com" mail_user="******" mail_pass="******" mail_postfix="mail.139.com" me = mail_user+"<"+mail_user+"@"+mail_postfix+">" msg = MIMEMultipart('related') msg['Subject'] = email.Header.Header(sub,'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(con, 'plain', 'utf-8') msgAlternative.attach(msgText) msg.attach(msgAlternative) try: s = smtplib.SMTP() s.connect(mail_host) s.login(mail_user,mail_pass) s.sendmail(me, to_list, msg.as_string()) s.quit() except Exception,e: return False
def multi( preamble = None, parts = [], **prepare_options ): """\ Assemble a multi-part MIME message. ``preamble`` Text to display before the message parts which will be seen only by email clients which don't support MIME. ``parts`` A list of the MIME parts to add to this message. You can use ``part()`` to create each part. ``**prepare_options`` Any extra keyword argument are sent to ``prepare()`` to add standard information to the message. """ message = MIMEMultipart() if preamble is not None: message.preamble = preamble for part in parts: message.attach(part) if prepare_options: message = prepare(message, **prepare_options) return message
def send_email(to, title): username = '******' password = '******' msgRoot = MIMEMultipart('related') msgRoot['Subject'] = title msgRoot['From'] = username msgRoot['To'] = to msgRoot.preamble = 'This is a multi-part message in MIME format.' msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) f=open('email.txt', 'r') msg = f.read() f.close() msgText = MIMEText(msg, 'html') msgAlternative.attach(msgText) ''' msg = "\r\n".join([ "From: %s" % fromaddr, "To: %s" % toaddrs, "Subject: Just a message", "", msg ]) ''' server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(username,password) server.sendmail(username, to, msgRoot.as_string()) server.quit()
def send_file_zipped(to, subject, text, attach): zf = tempfile.TemporaryFile(prefix='mail', suffix='.zip') zip = zipfile.ZipFile(zf, 'w') zip.write(attach) zip.close() zf.seek(0) mailuser=base64.b64decode('cGVsaXNhbGFjYXJ0YS5sb2dAZ21haWwuY29t') smtpserver='smtp.gmail.com' smtpport='587' mailpasswd=base64.b64decode('MjMwMTE5NzM=') # Create the message themsg = MIMEMultipart() themsg['Subject'] = subject themsg['To'] = to themsg['From'] = mailuser themsg.preamble = 'I am not using a MIME-aware mail reader.\n' msg = MIMEBase('application', 'zip') msg.set_payload(zf.read()) Encoders.encode_base64(msg) msg.add_header('Content-Disposition', 'attachment', filename=attach + '.zip') themsg.attach(msg) themsg = themsg.as_string() # send the message smtp = smtplib.SMTP(smtpserver, int(smtpport)) smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login(to, mailpasswd) smtp.sendmail(mailuser, to, themsg) smtp.close()
def _create_msg(): msg = MIMEMultipart('related') msg['Subject'] = 'Zabbix Screen Report: %s' % screen_name msg['From'] = me msg['To'] = ';'.join(to_list) msg.preamble = 'This is a multi-part message in MIME format.' contents = "<h1>Screen %s</h1><br>" % screen_name contents += "<table>" for g_name in graphs: with open(os.path.join(GRAPH_PATH, g_name), 'rb') as fp: msg_image = MIMEImage(fp.read()) msg_image.add_header('Content-ID', "<%s>" % g_name) msg.attach(msg_image) contents += '' contents += "<tr><td><img src='cid:%s'></td></tr>" % g_name contents += "</table>" msg_text = MIMEText(contents, 'html') msg_alternative = MIMEMultipart('alternative') msg_alternative.attach(msg_text) msg.attach(msg_alternative) return msg
def email_send(time): if time >= 60: message = "Graph Interface Fa0/4" sender = '*****@*****.**' recipient = '*****@*****.**' subject = "Interface fa0/4 graphs" msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = sender msg['To'] = recipient msg.preamble = 'Multipart massage.\n' part = MIMEText("Graph Interface Fa0/4") msg.attach(part) part = MIMEApplication(open("/home/arudas/git/pynet_class/class3/in_out_octets.svg","rb").read()) part.add_header('Content-Disposition', 'attachment', filename="in_out_octets.svg") msg.attach(part) part = MIMEApplication(open("/home/arudas/git/pynet_class/class3/in_out_packets.svg","rb").read()) part.add_header('Content-Disposition', 'attachment', filename="in_out_packets.svg") msg.attach(part) smtp_conn = smtplib.SMTP('localhost') smtp_conn.sendmail(sender, recipient, msg.as_string()) smtp_conn.quit() return True
def test_mail(request): msg = MIMEMultipart() msg['Subject'] = 'Test Multipart from tanglab' msg['From'] = '*****@*****.**' msg['To'] = '[email protected],[email protected]' msg.preamble = 'This is a test message again' fromaddr = "*****@*****.**" toaddrs = ['*****@*****.**', '*****@*****.**'] content = MIMEText( "Dear Tanglab User: Attached are the AMPL and SBML files we generated for you. -- Tanglab" ) msg.attach(content) fp = open('/research-www/engineering/tanglab/flux/temp/rak1.ampl', 'rb') ampl = MIMEText(fp.read()) ampl.add_header('Content-Disposition', 'attachment; filename="rak1.ampl"') fp.close() msg.attach(ampl) fp = open('/research-www/engineering/tanglab/flux/temp/ilo1.sbml', 'rb') sbml = MIMEText(fp.read()) sbml.add_header('Content-Disposition', 'attachment; filename="ilo1.sbml"') fp.close() msg.attach(sbml) server = smtplib.SMTP('localhost') server.sendmail(fromaddr, toaddrs, msg.as_string()) server.quit() return HttpResponse(content=" Even New Email sent. ", status=200, content_type="text/html")
def send_email(attach, filename, ktconfig): msg = MIMEMultipart() msg["subject"] = "Convert" msg["from"] = ktconfig['from_addr'] msg["to"] = ktconfig['kindle_email'] htmlText = "kindle reader delivery." msg.preamble = htmlText msgText = MIMEText(htmlText, 'html', 'utf-8') msg.attach(msgText) print filename with open(attach, 'rb') as f: att = MIMEText(f.read(), 'base64', 'utf-8') att["Content-Type"] = 'application/octet-stream' att["Content-Disposition"] = 'attachment; filename="%s.txt"' % ( filename) msg.attach(att) # 设置附件的MIME和文件名,这里是txt类型: if ktconfig['mail_ssl'] == True: server = smtplib.SMTP_SSL(timeout=60) else: server = smtplib.SMTP_SSL(timeout=60) server.connect(ktconfig['smtp_server'], ktconfig['smtp_port']) server.ehlo() server.set_debuglevel(1) server.login(ktconfig['from_addr'], ktconfig['password']) server.sendmail(ktconfig['from_addr'], ktconfig['kindle_email'], msg.as_string()) server.close()
def emailFile(to, subject, message, filePath, mimeType=None, fromEmail=FROMEMAIL, server=SERVER): """ sends an email attachment to the given address or list of addesses. if the mimeType is not specified, it uses mimetypes.guess_type to determine it. """ toList, to = processTo(to) msg = MIMEMultipart() msg['Subject'] = subject msg['To'] = to msg['From'] = fromEmail msg['Date'] = formatdate() msg.preamble = 'You are not using a MIME-aware reader\n' msg.epilogue = '' #add the main message msg.attach(MIMEText(message)) if type(filePath) is list: for f in filePath: addFile(f, msg, mimeType) else: addFile(filePath, msg, mimeType) rawEmail(toList, msg.as_string(), server=server, fromEmail=fromEmail)
def _send_email(sender, recipients, subject, smtp_host="localhost", body="", attachment_file=None): ''' :param sender: :param recipients: string or list of strings with emails :param subject: email subject :param smtp_host: SMTP host to use to send the email :param body: message body :param attachment_file: file to attach to the message ''' recipients_list = recipients if (type(recipients) is list) else [recipients] msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = sender msg['To'] = ','.join(recipients_list) msg.preamble = 'Multipart message.\n' msg.attach(MIMEText(body)) if attachment_file != None: with open(attachment_file, 'r') as fp: attachment = MIMEApplication(fp.read()) attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachment_file)) msg.attach(attachment) try: s = smtplib.SMTP(smtp_host) s.ehlo() s.sendmail(sender, recipients_list, msg.as_string()) s.quit() except smtplib.SMTPException as smtpe: sys.stderr.write("SMTPException occurred sending email:" + str(smtpe) + "\n") except Exception as e: sys.stderr.write("Exception occurred sending email: " + str(e) + "\n")
def SendEmail(authInfo, fromAdd, toAdd, subject, htmlText): strFrom = fromAdd strTo = toAdd server = authInfo.get('server') user = authInfo.get('user') passwd = authInfo.get('password') if not (server and user and passwd) : print 'incomplete login info, exit now' return # 设定root信息 msgRoot = MIMEMultipart('related') msgRoot['Subject'] = subject msgRoot['From'] = strFrom msgRoot['To'] = strTo msgRoot.preamble = 'This is a multi-part message in MIME format.' msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgText = MIMEText(htmlText, 'html', 'utf-8') msgAlternative.attach(msgText) #发送邮件 smtp = smtplib.SMTP() #设定调试级别,依情况而定 # smtp.set_debuglevel(1) smtp.connect(server) smtp.login(user, passwd) smtp.sendmail(strFrom, strTo, msgRoot.as_string()) smtp.quit()
def _send(self, toAddrs, ccAddrs, subject, textMsg, htmlMsg, attachments={}, highImportance=0): """Sends E-mails with the given information""" # Create the root message and fill in the from, to, and subject headers msgRoot = MIMEMultipart("related") msgRoot["Subject"] = subject msgRoot["From"] = SMTPUSER msgRoot["To"] = ", ".join(toAddrs) msgRoot["Cc"] = ", ".join(ccAddrs) if highImportance: msgRoot["Importance"] = "high" msgRoot.preamble = "This is a multi-part message in MIME format." # Encapsulate the plain and HTML versions of the message body in an # 'alternative' part, so message agents can decide which they want to display. msgAlternative = MIMEMultipart("alternative") msgRoot.attach(msgAlternative) msgAlternative.attach(MIMEText(textMsg)) msgAlternative.attach(MIMEText(htmlMsg, "html")) for name, filePath in attachments.items(): msgAttachment = MIMEBase("application", "octet-stream") msgAttachment.set_payload(open(filePath, "rb").read()) Encoders.encode_base64(msgAttachment) msgAttachment.add_header("Content-Disposition", 'attachment; filename="%s"' % os.path.basename(filePath)) msgRoot.attach(msgAttachment) # Send the email smtp = smtplib.SMTP() smtp.connect(SMTPSERVER, SMTPPORT) if SMTPUSER and SMTPPASSWORD: smtp.login(SMTPUSER, SMTPPASSWORD) smtp.sendmail(SMTPUSER, toAddrs, msgRoot.as_string()) smtp.quit()
def emailCharts(fromaddr, toaddrs, subject, charts, server, username, password): msgRoot = MIMEMultipart() msgRoot['Subject'] = subject msgRoot['From'] = fromaddr msgRoot['To'] = toaddrs msgRoot.preamble = subject msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgText = MIMEText(subject) msgAlternative.attach(msgText) html = '<br>' for chart in charts: html = html + '<img src="cid:' + chart[0] + '"><br>' msgText = MIMEText(html, 'html') msgAlternative.attach(msgText) for chart in charts: fp = open(chart[1], 'rb') img = MIMEImage(fp.read()) fp.close() img.add_header('Content-ID', '<' + chart[0] + '>') msgRoot.attach(img) smtp = smtplib.SMTP(server) smtp.starttls() smtp.login(username, password) smtp.sendmail(fromaddr, toaddrs, msgRoot.as_string()) smtp.quit()
def sendmail(toAddr, subject, textPart, htmlPart=None, fromAddr="*****@*****.**", fromName="Flocked-in"): if textPart: textPart = sanitizer.unescape(textPart, {":": ":"}) if htmlPart: msg = MIMEMultipart("alternative") msg.preamble = "This is a multi-part message in MIME format." msgText = MIMEText(textPart, _charset="utf8") msg.attach(msgText) msgText = MIMEText(htmlPart, "html", _charset="utf8") msg.attach(msgText) else: msg = MIMEText(textPart, _charset="utf8") msg["Subject"] = sanitizer.unescape(subject, {":": ":"}) msg["From"] = "%s <%s>" % (fromName, fromAddr) msg["To"] = toAddr try: devMailId = config.get("Devel", "MailId") if devMailId: toAddr = devMailId except: pass message = msg.as_string() host = config.get("SMTP", "Host") yield smtp.sendmail(host, fromAddr, toAddr, message)
def _send(self, toAddrs, ccAddrs, subject, textMsg, htmlMsg, attachments={}, highImportance=0): '''Sends E-mails with the given information''' # Create the root message and fill in the from, to, and subject headers msgRoot = MIMEMultipart('related') msgRoot['Subject'] = subject msgRoot['From'] = SMTPUSER msgRoot['To'] = ', '.join(toAddrs) msgRoot['Cc'] = ', '.join(ccAddrs) if highImportance: msgRoot['Importance'] = "high" msgRoot.preamble = 'This is a multi-part message in MIME format.' # Encapsulate the plain and HTML versions of the message body in an # 'alternative' part, so message agents can decide which they want to display. msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgAlternative.attach(MIMEText(textMsg)) msgAlternative.attach(MIMEText(htmlMsg,'html')) for name, filePath in list(attachments.items()): msgAttachment = MIMEBase('application', "octet-stream") msgAttachment.set_payload( open(filePath,"rb").read() ) Encoders.encode_base64(msgAttachment) msgAttachment.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(filePath)) msgRoot.attach(msgAttachment) # Send the email smtp = smtplib.SMTP() smtp.connect(SMTPSERVER, SMTPPORT) if SMTPUSER and SMTPPASSWORD: smtp.login(SMTPUSER, SMTPPASSWORD) smtp.sendmail(SMTPUSER, toAddrs, msgRoot.as_string()) smtp.quit()
def send_an_email(): toaddr = '*****@*****.**' # To id me = '*****@*****.**' # your id subject = "picture" # Subject msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = me msg['To'] = toaddr msg.preamble = "test " #msg.attach(MIMEText(text)) part = MIMEBase('application', "octet-stream") part.set_payload(open("image.jpg", "rb").read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="image.jpg"') # File name and format name msg.attach(part) try: s = smtplib.SMTP('smtp.gmail.com', 587) # Protocol s.ehlo() s.starttls() s.ehlo() s.login(user = '******', password = '******') # User id & password #s.send_message(msg) s.sendmail(me, toaddr, msg.as_string()) s.quit() #except: # print ("Error: unable to send email") except SMTPException as error: print ("Error") # Exception
def send_email(image, config): msg_root = MIMEMultipart('related') msg_root['Subject'] = 'Security Update' msg_root['From'] = config.sender_email_address msg_root['To'] = config.receiver_email_address msg_root.preamble = 'Raspberry pi security camera update' msg_alternative = MIMEMultipart('alternative') msg_root.attach(msg_alternative) msg_text = MIMEText('Smart security cam found object') msg_alternative.attach(msg_text) msg_text = MIMEText('<img src="cid:image1">', 'html') msg_alternative.attach(msg_text) msg_image = MIMEImage(image) msg_image.add_header('Content-ID', '<image1>') msg_root.attach(msg_image) smtp = smtplib.SMTP('smtp.gmail.com', 587) smtp.starttls() smtp.login(config.sender_email_address, config.sender_email_password) smtp.sendmail(config.sender_email_address, config.receiver_email_address, msg_root.as_string()) smtp.quit()
def sendEmail(name, pictureString): import smtplib from email.MIMEImage import MIMEImage from email.MIMEMultipart import MIMEMultipart COMMASPACE = ', ' SMTP_SERVER = 'smtp.gmail.com' SMTP_PORT = 587 msg = MIMEMultipart() msg['Subject'] = 'The name of the burglar is ' + name + "." msg['From'] = '*****@*****.**' msg['To'] = COMMASPACE.join('*****@*****.**') msg.preamble = 'The name of the burglar is '# + str(name) + "." fp = open(pictureString, 'rb') img = MIMEImage(fp.read()) fp.close() msg.attach(img) s = smtplib.SMTP(SMTP_SERVER, SMTP_PORT) s.ehlo() s.starttls() s.ehlo() s.login('*****@*****.**', '$anFi3rro') s.sendmail('*****@*****.**', '*****@*****.**' , msg.as_string()) s.quit() return
def emailAggregatorPage(from_addr, to_addr, subj, smtp_host, out_fn): """ Read in the HTML page produced by an aggregator run, construct a MIME-Multipart email message with the HTML attached, and send it off with the given from, to, and subject headers using the specified SMTP mail server. """ # Begin building the email message. msg = MIMEMultipart() msg['To'] = to_addr msg['From'] = from_addr msg['Subject'] = subj msg.preamble = "You need a MIME-aware mail reader.\n" msg.epilogue = "" # Generate a plain text alternative part. plain_text = """ This email contains entries from your subscribed feeds in HTML. """ part = MIMEText(plain_text, "plain", UNICODE_ENC) msg.attach(part) # Generate the aggregate HTML page, read in the HTML data, attach it # as another part of the email message. html_text = open(out_fn).read() part = MIMEText(html_text, "html", UNICODE_ENC) msg.attach(part) # Finally, send the whole thing off as an email message. print "Sending email '%s' to '%s'" % (subj, to_addr) s = smtplib.SMTP(smtp_host) s.sendmail(from_addr, to_addr, msg.as_string()) s.close()
def sendEmail(self, toAddr, subject, htmlText): # 设定root信息 msgRoot = MIMEMultipart('related') msgRoot['Subject'] = subject msgRoot['To'] = toAddr msgRoot.preamble = 'This is a multi-part message in MIME format.' # Encapsulate the plain and HTML versions of the message body in an # 'alternative' part, so message agents can decide which they want to display. msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) #设定HTML信息 msgText = MIMEText(htmlText, 'html', 'utf-8') msgAlternative.attach(msgText) #发送邮件 succeed = False for authInfo in self._auth: smtp = smtplib.SMTP() try: msgRoot['From'] = authInfo["from"] smtp.connect(authInfo["server"], authInfo["port"]) smtp.login(authInfo["user"], authInfo["password"]) smtp.sendmail(authInfo["from"], toAddr.rstrip(";").split(";"), msgRoot.as_string()) succeed = True print 'succeed!' break except Exception, e: print >> sys.stderr, 'error sending mail with ' + str(authInfo) print >> sys.stderr, 'error info: ' + str(e) print >> sys.stderr, 'change to next stmp server'
def send_email(debug,toaddr2,msgsubject,fromaddr,template,smtp_server,username,password): replyto = fromaddr htmlmsgtext = template msgtext = htmlmsgtext.replace('<b>','').replace('</b>','').replace('<br>',"\r").replace('</br>',"\r").replace('<br/>',"\r").replace('</a>','') msgtext = re.sub('<.*?>','',msgtext) msg = MIMEMultipart() msg.preamble = 'This is a multi-part message in MIME format.\n' msg.epilogue = '' body = MIMEMultipart('alternative') body.attach(MIMEText(msgtext)) body.attach(MIMEText(htmlmsgtext, 'html')) msg.attach(body) msg.add_header('From', fromaddr) msg.add_header('To', toaddr2) msg.add_header('Subject', msgsubject) msg.add_header('Reply-To', replyto) server = smtplib.SMTP(smtp_server) if debug == True: server.set_debuglevel(True) server.starttls() server.login(username,password) server.sendmail(msg['From'], [msg['To']], msg.as_string()) print ">sent email" server.quit() print ">closed session"
def sendEmail(image): msgRoot = MIMEMultipart('related') ts = datetime.datetime.now().strftime("%A %d %B %Y %I :%M:%S%p") msgRoot['Subject'] = 'Security Update: ' + ts msgRoot['From'] = fromEmail msgRoot['To'] = toEmail msgRoot.preamble = 'Raspberry pi security camera update' msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgText = MIMEText('Smart security cam found object') msgAlternative.attach(msgText) msgText = MIMEText('<img src="cid:image1">', 'html') msgAlternative.attach(msgText) msgImage = MIMEImage(image) msgImage.add_header('Content-ID', '<image1>') msgRoot.attach(msgImage) smtp = smtplib.SMTP('smtp.gmail.com', 587) smtp.starttls() smtp.login(fromEmail, fromEmailPassword) smtp.sendmail(fromEmail, toEmail, msgRoot.as_string()) smtp.quit()
def send_multipart_email(subject, text_part1, text_part2, img_url, replyto, to_list): msgRoot = MIMEMultipart("related") msgRoot["Subject"] = subject msgRoot["From"] = FROM msgRoot["To"] = ", ".join(to_list) msgRoot.add_header("reply-to", replyto) msgRoot.preamble = "This is a multi-part message in MIME format." msgAlternative = MIMEMultipart("alternative") msgRoot.attach(msgAlternative) msgText = MIMEText(text_part1 + text_part2) msgAlternative.attach(msgText) msgText = MIMEText( text_part1.replace("\r\n", "<br />") + '<img src="cid:image1">' + text_part2.replace("\r\n", "<br />"), "html" ) msgAlternative.attach(msgText) content = urllib2.urlopen(img_url).read() msgImage = MIMEImage(content) msgImage.add_header("Content-ID", "<image1>") msgRoot.attach(msgImage) smtp = smtplib.SMTP() smtp.connect("smtp.gmail.com", 587) smtp.ehlo() smtp.starttls() smtp.login(gmail_user, gmail_pwd) smtp.sendmail(FROM, to_list, msgRoot.as_string()) smtp.quit()
def my_send_mail(subject, txt, sender, to=[], files=[], charset='UTF-8'): import os from django.core.mail import send_mail from email import Encoders from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from django.conf import settings from django.core.mail import EmailMultiAlternatives for dest in to: dest = dest.strip() msg = MIMEMultipart('related') msg['Subject'] = subject msg['From'] = sender msg['To'] = dest msg.preamble = 'This is a multi-part message in MIME format.' msgAlternative = MIMEMultipart('alternative') msg.attach(msgAlternative) msgAlternative.attach(MIMEText(txt, _charset=charset)) msgAlternative.attach(MIMEText(txt, 'html', _charset=charset)) #msg.attach_alternative(txt, "text/html") for f in files: part = MIMEBase('application', "octet-stream") part.set_payload( open(f,"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) from smtplib import SMTP smtp = SMTP() smtp.connect(host=settings.EMAIL_HOST) smtp.sendmail(sender,dest, msg.as_string()) smtp.quit()
def emailAggregatorPage(from_addr, to_addr, subj, smtp_host, out_fn): """ Read in the HTML page produced by an aggregator run, construct a MIME-Multipart email message with the HTML attached, and send it off with the given from, to, and subject headers using the specified SMTP mail server. """ # Begin building the email message. msg = MIMEMultipart() msg['To'] = to_addr msg['From'] = from_addr msg['Subject'] = subj msg.preamble = "You need a MIME-aware mail reader.\n" msg.epilogue = "" # Generate a plain text alternative part. plain_text = """ This email contains entries from your subscribed feeds in HTML. """ part = MIMEText(plain_text, "plain", UNICODE_ENC) msg.attach(part) # Generate the aggregate HTML page, read in the HTML data, attach it # as another part of the email message. html_text = open(out_fn).read() part = MIMEText(html_text, "html", UNICODE_ENC) msg.attach(part) # Finally, send the whole thing off as an email message. print "Sending email '%s' to '%s'" % (subj, to_addr) s = smtplib.SMTP(smtp_host) s.sendmail(from_addr, to_addr, msg.as_string()) s.close()
def sendEmail(htmlText): msgRoot = MIMEMultipart('related') msgRoot['Subject'] = 'testtttttttttttt' msgRoot['From'] = user msgRoot['To'] = user msgRoot.preamble = 'This is a multi-part message in MIME format.' msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgText = MIMEText(htmlText, 'html', 'utf-8') msgText.set_charset("utf-8") msgAlternative.attach(msgText) smtp =smtplib.SMTP('smtp.gmail.com', port=587, timeout=20) smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login(user, passwd) smtp.sendmail(user, user, msgRoot.as_string()) sleep(5) smtp.quit() return
def send_email(to, title, *holdplace): username = '******' password = '******' msgRoot = MIMEMultipart('related') msgRoot['Subject'] = title msgRoot['From'] = username msgRoot['To'] = to msgRoot.preamble = 'This is a multi-part message in MIME format.' msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) f = open('email.txt', 'r') msg = f.read() f.close() msg = msg % holdplace msgText = MIMEText(msg, 'html') msgAlternative.attach(msgText) ''' msg = "\r\n".join([ "From: %s" % fromaddr, "To: %s" % toaddrs, "Subject: Just a message", "", msg ]) ''' server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(username, password) server.sendmail(username, to, msgRoot.as_string()) server.quit()
def main(): images = os.listdir(IMAGE_DIR) encoded_images = {} strFrom = '' strTo = '' msgRoot = MIMEMultipart('alternative') msgRoot['Subject'] = "" msgRoot['To'] = strTo msgRoot['From'] = strFrom msgRoot.preamble = 'This is a multi-part message in MIME format.' with open('text.txt', 'r') as text: text = text.read() msgRoot.attach(MIMEText(text)) if not images: msgRoot.attach(MIMEText(render_template(), 'html')) else: msgRelated = MIMEMultipart('related') msgRelated.attach(MIMEText(render_template(images), 'html')) for image in images: with open(image, 'rb') as img: byte_data = img.read() msgImage = MIMEImage(byte_data) msgImage.add_header('Content-ID', image) msgRelated.attach(msgImage) b64 = b64encode(byte_data) encoded_images[image]=b64 msgRoot.attach(msgRelated) with open("../../public_html/preview.html", 'w') as preview: preview.write(render_template(images, preview=encoded_images)) print(msgRoot.as_string())
def user_password_retrieve(request): username = request.GET['username_forgot'] u = User.objects.get(email=username) token_generator = PasswordResetTokenGenerator() token = token_generator.make_token(u) u.set_password(token) u.save() msg = MIMEMultipart() msg['Subject'] = 'Mail from the MicrobesFlux -- Password reset' msg['From'] = '*****@*****.**' msg['To'] = username msg.preamble = 'Reset your password' fromaddr = "*****@*****.**" toaddrs = [ username, ] content = MIMEText( "Dear MicrobesFlux User: we have changed your password to " + token + ". -- MicrobesFlux") msg.attach(content) server = smtplib.SMTP('localhost') server.sendmail(fromaddr, toaddrs, msg.as_string()) server.quit() return HttpResponse(content="""New Email sent!""", status=200, content_type="text/html")
def send_email_to_list(debug,line,fromaddr,template,smtp_server,msgsubject,username,password): replyto = fromaddr htmlmsgtext = template try: msgtext = htmlmsgtext.replace('<b>','').replace('</b>','').replace('<br>',"\r").replace('</br>',"\r").replace('<br/>',"\r").replace('</a>','') msgtext = re.sub('<.*?>','',msgtext) msg = MIMEMultipart() msg.preamble = 'This is a multi-part message in MIME format.\n' msg.epilogue = '' body = MIMEMultipart('alternative') body.attach(MIMEText(msgtext)) body.attach(MIMEText(htmlmsgtext, 'html')) msg.attach(body) msg.add_header('From', fromaddr) msg.add_header('To', line) msg.add_header('Subject', msgsubject) msg.add_header('Reply-To', replyto) server = smtplib.SMTP(smtp_server) if debug == True: server.set_debuglevel(True) server.starttls() server.login(username,password) server.sendmail(msg['From'], [msg['To']], msg.as_string()) print ">sent to: ",line server.quit() print ">closed session" print ">sleeping, dont want to flood smtp server" time.sleep(1) except Exception,e: print str(e) print ">error sending email ",line
def send_mail(etc=""): open_ports = get_ports() ports = pickle.load(open("tcp_ports", "rb")) text = """ Open Ports:<br><br> <table cellspacing="15"> <tr> <th>Port</th> <th>Service</th> </tr> """ for p in open_ports: text += "<tr><td>%s</td><td>%s</td></tr>" % (p, lsofi(p)) parser = SafeConfigParser() parser.read("./stats.conf") msg = MIMEMultipart('related') msg['Subject'] = "Traffic report from %s" % (socket.getfqdn()) msg['From'] = parser.get('email', 'from') msg['To'] = parser.get('email', 'to') msg.preamble = 'This is a multi-part message in MIME format.' body = """ %s<br><br> <img src="cid:graph_packets"><br><br> <img src="cid:graph_conns"><br><br> <img src="cid:graph_bandwidth"><br><br>%s</table>""" % (etc, text) msgBody = MIMEText(body, 'html') msg.attach(msgBody) attachments = [ ('packets.png', 'graph_packets'), ('conns.png', 'graph_conns'), ('bps.png', 'graph_bandwidth') ] for attachment in attachments: fp = open(attachment[0], 'rb') img = MIMEImage(fp.read()) img.add_header('Content-ID', attachment[1]) fp.close() msg.attach(img) s = smtplib.SMTP(parser.get('email', 'smtp_server'), parser.getint('email', 'port')) if parser.getboolean('email', 'auth'): s.ehlo() if parser.getboolean('email', 'use_tls'): s.starttls() s.ehlo() if parser.getboolean('email', 'auth'): s.login(parser.get('email', 'username'), parser.get('email', 'password')) s.sendmail(parser.get('email', 'from'), [parser.get('email', 'to')], msg.as_string()) s.quit()
def build_mail(subject, text, address_from, address_to, address_cc=None, images=None): from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.MIMEImage import MIMEImage msgRoot = MIMEMultipart('related') msgRoot['Subject'] = subject msgRoot['From'] = address_from msgRoot['To'] = address_to #text_msg = MIMEText(text) #msgRoot.attach(text_msg) msgRoot.preamble = 'This is a multi-part message in MIME format.' # Encapsulate the plain and HTML versions of the message body in an # 'alternative' part, so message agents can decide which they want to display. msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgContent = MIMEText(text, 'html', 'utf-8') msgAlternative.attach(msgContent) return msgRoot
def smtp_process(self, alstr_to, astr_from, astr_subject, astr_body, alstr_attach): # # PRECONDITIONS # o Should only be called by one of the send() methods # o Assumes that any attachments are valid files # # POSTCONDITIONS # o Interacts with the SMTPlib module # self.internals_check() print astr_from msg = MIMEMultipart() msg['Subject'] = astr_subject msg['From'] = astr_from msg.preamble = "This is a mult-part message in MIME format." msg.attach(MIMEText(astr_body)) msg.epilogue = '' for file in alstr_attach: fp = open(file, 'rb') img = MIMEImage(fp.read()) img.add_header('Content-ID', file) fp.close() msg.attach(img) smtp = smtplib.SMTP() smtp.connect(self.mstr_SMTPserver) for str_to in alstr_to: msg['To'] = str_to smtp.sendmail(astr_from, str_to, msg.as_string()) smtp.close()
def mail(self): msg = MIMEMultipart('related') msg.preamble = 'This is a multi-part message in MIME format' if self.csv is not None: txt = MIMEText(self.comment, 'plain') msg.attach(txt) csv = MIMEBase('application', 'vnd.ms-excel') csv.add_header('Content-ID', '<Zenoss Report>') csv.add_header('Content-Disposition', 'attachment', filename='zenoss_report.csv') csv.set_payload(self.csv) msg.attach(csv) else: txt = MIMEText(''.join(self.html), 'html') msg.attach(txt) for url, (name, img) in self.images.items(): ctype, encoding = mimetypes.guess_type(url) if ctype == None: ctype = 'image/png' maintype, subtype = ctype.split('/', 1) img = MIMEImage(img, subtype) img.add_header('Content-ID', '<%s>' % name) msg.attach(img) return msg
def send_charter_email(context, pdf, to, sender, body, language): """ sending the charter by mail """ mailhost = context.MailHost msg = MIMEMultipart() msg['Subject'] = translate(_(u"campaign_name", default=u"Healthy Workplaces"), target_language=language) msg['From'] = sender msg['To'] = to msg['Date'] = formatdate(localtime=True) msg.preamble = 'You will not see this in a MIME-aware mail reader.\n' params = dict(charset='utf-8') part = MIMEBase('text', 'html', **params) part.set_payload(body) msg.attach(part) part = MIMEBase('application', 'octet-stream') part.set_payload(pdf) Encoders.encode_base64(part) part.add_header( 'Content-Disposition', 'attachment; filename="campaign-certificate.pdf"', ) msg.attach(part) mailhost._send(sender, to, msg.as_string())
def send_from_gmail(email, body, subject): ''' Send email from gmail.''' server = SMTP('smtp.gmail.com', 587) ## server.set_debuglevel(1) server.ehlo() server.starttls() server.ehlo() server.login(EMAIL_LOGIN, EMAIL_PASSWORD) # Create the enclosing (outer) message outer = MIMEMultipart() outer['Subject'] = subject outer['To'] = email outer['From'] = EMAIL_LOGIN outer.preamble = '\n' # To guarantee the message ends with a newline outer.epilogue ='' # Note: we should handle calculating the charset msg = MIMEText(body) # Message body outer.attach(msg) text = outer.as_string() server.sendmail(outer['From'], outer['To'], text) # SSL error because of bad comunication closing try: server.quit() except: pass
def main(): msgRoot = MIMEMultipart('alternative') msgRoot.preamble = 'This is a multi-part message in MIME format.' with open(TEXT_FILE, 'r') as txt_f: text = txt_f.read() msgRoot.attach(MIMEText(text)) with open(HTML_FILE,'r') as html_f: html = html_f.read() if IMAGES: msgRelated = MIMEMultipart('related') msgRelated.attach(MIMEText(html, 'html')) for image in IMAGES: with open(image, 'rb') as img: msgImage = MIMEImage(img.read()) msgImage.add_header('Content-ID', os.path.split(image)[1]) ## clean up to remove the folder location in the for cid msgRelated.attach(msgImage) msgRoot.attach(msgRelated) else: msgRoot.attach(MIMEText(html, 'html')) if SEND: msgRoot['To'] = SEND[0] msgRoot['From'] = SEND[1] msgRoot['Subject'] = SEND[2] smtp = smtplib.SMTP('localhost') smtp.sendmail(SEND[0], SEND[1], msgRoot.as_string()) smtp.quit() print(msgRoot.as_string())
def main(argv=None): if argv is None: argv = sys.argv print argv # Check how many arguments were passed, minimum is 4 if len(argv) <= 4: print "Usage: python hadoop_mailer.py [SUBJECT] [starting|complete] [from(domain)] [to(email@address)] [[MSG(body)] | [\"{'text':'', 'html':'', 'version':'', 'cluster':''}\"]]" sys.exit(0) # Define Email and Server Variables SERVER = "localhost" #SERVER = "207.67.226.5" FROM = "analytics@%s" % argv[3] TO = ["%s" % argv[4]] # must be a list SUBJECT = "Analytics %s is %s" % (argv[1], argv[2]) # msgRoot will be sent to smtp. msgRoot = MIMEMultipart('related') msgRoot['Subject'] = SUBJECT msgRoot['From'] = FROM msgRoot['To'] = ", ".join(TO) msgRoot.preamble = 'This is a multi-part message in MIME format.' print "===>arg[0] = %s; arg[1]=%s; argv[2]=%s; argv[3]=%s; argv[4]=%s" %(argv[0], argv[1], argv[2], argv[3], argv[4]) details = {} if len(argv) > 5: try: details = ast.literal_eval(argv[5]) except: try: details = eval(argv[5]) #compiler.parse(argv[5],"eval") except SyntaxError, err: details['text'] = argv[5]
def multi(preamble=None, parts=[], **prepare_options): """\ Assemble a multi-part MIME message. ``preamble`` Text to display before the message parts which will be seen only by email clients which don't support MIME. ``parts`` A list of the MIME parts to add to this message. You can use ``part()`` to create each part. ``**prepare_options`` Any extra keyword argument are sent to ``prepare()`` to add standard information to the message. """ message = MIMEMultipart() if preamble is not None: message.preamble = preamble for part in parts: message.attach(part) if prepare_options: message = prepare(message, **prepare_options) return message
def create_html_mail(subject, html, text=None, from_addr=None, to_addr=None, headers=None, encoding='UTF-8'): """Create a mime-message that will render HTML in popular MUAs, text in better ones. """ # Use DumbWriters word wrapping to ensure that no text line # is longer than plain_text_maxcols characters. plain_text_maxcols = 72 html = html.encode(encoding) if text is None: # Produce an approximate textual rendering of the HTML string, # unless you have been given a better version as an argument textout = StringIO.StringIO() formtext = formatter.AbstractFormatter( formatter.DumbWriter(textout, plain_text_maxcols)) parser = htmllib.HTMLParser(formtext) parser.feed(html) parser.close() # append the anchorlist at the bottom of a message # to keep the message readable. counter = 0 anchorlist = "\n\n" + ("-" * plain_text_maxcols) + "\n\n" for item in parser.anchorlist: counter += 1 anchorlist += "[%d] %s\n" % (counter, item) text = textout.getvalue() + anchorlist del textout, formtext, parser, anchorlist else: text = text.encode(encoding) # if we would like to include images in future, there should # probably be 'related' instead of 'mixed' msg = MIMEMultipart('mixed') # maybe later :) msg['From'] = Header("%s <%s>" % # (send_from_name, send_from), encoding) msg['Subject'] = Header(subject, encoding) msg['From'] = from_addr msg['To'] = to_addr msg['Date'] = formatdate(localtime=True) msg["Message-ID"] = email.Utils.make_msgid() if headers: for key, value in headers.items(): msg[key] = value msg.preamble = 'This is a multi-part message in MIME format.' alternatives = MIMEMultipart('alternative') msg.attach(alternatives) alternatives.attach(MIMEText(text, 'plain', _charset=encoding)) alternatives.attach(MIMEText(html, 'html', _charset=encoding)) return msg
def emailImage(self): logging.debug("emailImage() called") self.captureImage() # if RECORDVIDEO or RECORDTIMELAPSE: # return # Create the root message and fill in the from, to, and subject headers msgRoot = MIMEMultipart('related') msgRoot['Subject'] = 'Motion detected' msgRoot['From'] = emailFromAddress msgRoot[ 'To'] = 'Security Team for camera ' + thisDeviceName # emailAddressTo msgRoot.preamble = 'This is a multi-part message in MIME format.' # Encapsulate the plain and HTML versions of the message body in an # 'alternative' part, so message agents can decide which they want to display. msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgText = MIMEText(emailTextAlternate) msgAlternative.attach(msgText) # We reference the image in the IMG SRC attribute by the ID we give it below msgText = MIMEText( '<b>Alert <i>motion detected</i> on camera %s</b> and here is a picture of what/whomever triggered this alert! <br><img src="cid:image1"><br>^^^ The Culprit ^^^' % (thisDeviceName), 'html') msgAlternative.attach(msgText) self.imgStream.seek(0L) msgImage = MIMEImage(self.imgStream.read()) # Define the image's ID as referenced above msgImage.add_header('Content-ID', '<image1>') msgRoot.attach(msgImage) # Send the email (this example assumes SMTP authentication is required) self.smtp.connect(emailServer, emailPort) self.smtp.starttls( ) # TODO: Can this be moved out of the iteration? Is it expensive? self.smtp.login(emailAccount, emailPassword) self.smtp.sendmail(emailFromAddress, emailAddressTo, msgRoot.as_string()) self.smtp.quit( ) # TODO: Determine if this can be elsewhere, or if we can leave this open. self.lastEmailTicks = time.time() if SAVEEMAILEDIMAGES: fname = '{saveimagedir}emailedSecurityCameraImage-{date}.jpg'.format( saveimagedir=SAVEIMAGEDIR, date=datetime.datetime.now().isoformat()) outf = file(fname, 'wb') self.imgStream.seek(0L) outf.write(self.imgStream.read()) outf.close() logging.info( 'Emailed and saved image to "{fname}"'.format(fname=fname)) else: logging.info('Emailed image at {currenttime}'.format( currenttime=datetime.datetime.now().isoformat()))
def sendEmail(authInfo, fromAdd, toAdd, subject, plainText, htmlText, attpath ,attName,attName2): strFrom = fromAdd strTo = toAdd server = authInfo.get('server') user = authInfo.get('user') passwd = authInfo.get('password') if not (server and user and passwd) : print 'incomplete login info, exit now' return msgRoot = MIMEMultipart('related') msgRoot['Subject'] = subject msgRoot['From'] = strFrom msgRoot['To'] = ', '.join(strTo) msgRoot.preamble = 'This is a multi-part message in MIME format.' msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgText = MIMEText(plainText, 'plain', 'utf-8') msgAlternative.attach(msgText) msgText = MIMEText(htmlText, 'html', 'utf-8') msgAlternative.attach(msgText) fp = open(attpath+attName, 'rb') msgImage1 = MIMEBase('application',"octet-stream") msgImage1.set_payload(fp.read()) fp.close() msgImage1.add_header('Content-Disposition', 'attachment; filename='+attName) email.Encoders.encode_base64(msgImage1) msgRoot.attach(msgImage1) if attName2 != '': fp = open(attpath+attName2, 'rb') msgImage = MIMEBase('application',"octet-stream") msgImage.set_payload(fp.read()) fp.close() msgImage.add_header('Content-Disposition', 'attachment; filename='+attName2) email.Encoders.encode_base64(msgImage) msgRoot.attach(msgImage) #smtp = smtplib.SMTP() #smtp.connect(server) #smtp.ehlo() #smtp.login(user, passwd) #smtp.sendmail(strFrom, strTo, msgRoot.as_string()) #smtp.quit() smtp=smtplib.SMTP_SSL(server,465) #smtp.set_debuglevel(1) smtp.login(user,passwd)#认证 smtp.sendmail(strFrom,strTo,msgRoot.as_string()) smtp.quit() return
def make_multipart_message(*parts): msg = MIMEMultipart('related') msg.preamble = 'This is a multi-part message in MIME format.' alt = MIMEMultipart('alternative') msg.attach(alt) for part in parts: alt.attach(part) return msg