def sendMail(to,subject,text, image): msg = MIMEMultipart('related') msg['From'] = user msg['To'] = to msg['Subject'] = subject msgText = MIMEText(text) msg.attach(msgText) fp = open(image, 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<image1>') msg.attach(msgImage) try: smtpServer = smtplib.SMTP('smtp.gmail.com', 587) 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.\n" except: print "[-] Sending Mail Failed."
def send_email(from_address, to_address, body, SUBJECT = ""): #from_address = "*****@*****.**" #to_address = from_address #SUBJECT = "THIS IS A TEST" PASSWORD = "" server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(from_address, PASSWORD) msg = MIMEMultipart() msg['From'] = from_address msg['To'] = to_address msg['Subject'] = SUBJECT # Input Message body text below: #body = "This is a test email, generated by send_email.py\nThis text should be on a new line." msg.attach(MIMEText(body, 'plain')) text = msg.as_string() server.sendmail(from_address, to_address, text) server.quit()
def email_results(msg_body): from_address = "*****@*****.**" recipients = ['*****@*****.**', '*****@*****.**'] to_address = ", ".join(recipients) msg = MIMEMultipart() msg['From'] = from_address msg['To'] = to_address msg['Subject'] = "FundBot" msg.attach(MIMEText(msg_body, 'plain')) for filename in os.listdir(os.path.join("plots")): if filename.endswith(".png"): attachment = open(os.path.join("plots", filename), "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) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(from_address, "123456789") text = msg.as_string() server.sendmail(from_address, to_address, text) server.quit()
def sendMail(cfg, bodyDatas, title): to_addr = cfg.EMail subject = '竞标提示:人脸识别' # msg = MIMEText('你好', 'text', 'utf-8') # 中文需参数‘utf-8’,单字节字符不需要 # msg['Subject'] = Header(subject, 'utf-8') msg = MIMEMultipart() msg['From'] = SEND_ADDRESS msg['To'] = to_addr # msg['Cc'] = ccaddr msg['Subject'] = "竞标提示===>>" + title body = "竞标提示:请关注以下新增招标" for one in bodyDatas: body = "%s \n %s" % (body, one) body = body.encode("utf-8") msg.attach(MIMEText(body, 'plain')) smtp = smtplib.SMTP() smtp.connect(SMTP_SERVER) smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.set_debuglevel(0) smtp.login(SEND_ADDRESS, MAIL_PASSWORD) smtp.sendmail(SEND_ADDRESS, to_addr, msg.as_string()) smtp.quit()
def _send_new_password(self): player_login = self.line_edit_player_login.text() try: from_adress = "*****@*****.**" to_adress = ui_defs.players_infos(player_login)["email"] email_to_send = MIMEMultipart() email_to_send['From'] = from_adress email_to_send['To'] = to_adress email_to_send['Subject'] = 'New Time Bomb Password' new_password = ui_defs.generate_random_password() self._assign_password_to_player(player_login, new_password) email_body = ( 'Your new time bomb password : '******'ll could change it in your preferences.\n\nSee you soon in game!" ) email_to_send.attach(MIMEText(email_body, 'plain')) gmail_server = smtplib.SMTP('smtp.gmail.com', 587) gmail_server.starttls() gmail_server.login(from_adress, "TimeBomb78+") gmail_server.sendmail(from_adress, to_adress, str(email_to_send)) gmail_server.quit() ui_defs.message_box('OK', 'A new password has been send.') self.close() except KeyError: ui_defs.message_box('Wrong Login', 'This login doesn\'t exist.')
def send_rate_email(sender, receiver, cc_receiver, to, txt, title): # to = _format_addr(to) subject = title table = """ %s """ % (txt) msg = MIMEMultipart('related') msgAlternative = MIMEMultipart('alternative') msg.attach(msgAlternative) msgText = MIMEText(table, 'html', 'utf-8') msgAlternative.attach(msgText) msg["Accept-Language"] = "zh-CN" msg["Accept-Charset"] = "ISO-8859-1,utf-8" if not isinstance(subject, unicode): subject = unicode(subject) msg['Subject'] = subject msg['To'] = ','.join(to) if cc_receiver != None: msg['CC'] = ','.join(cc_receiver) #----------------------------------------------------------- s = smtplib.SMTP('corp.chinacache.com') answer = s.sendmail(sender, receiver, msg.as_string()) s.close() logger.info( 'send_rate_email to: %s|| cc_receiver: %s|| receiver: %s|| answer: %s' % (to, cc_receiver, receiver, answer)) if str(answer) == '{}': return 'success' else: return 'fail'
def sendEmail(from_address, to_address, body, SUBJECT = "", attach_path = ""): #from_address = "*****@*****.**" #to_address = from_address #SUBJECT = "THIS IS A TEST" passw_path = "/home/pi/Documents/Python_files/password.txt" PASSWORD = getPass_or_Email(passw_path) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(from_address, PASSWORD) msg = MIMEMultipart() msg['From'] = from_address msg['To'] = to_address msg['Subject'] = SUBJECT # Input Message body text below: #body = "This is a test email, generated by send_email.py\nThis text should be on a new line." msg.attach(MIMEText(body, 'plain')) with open(attach_path) as f: part = MIMEApplication( f.read(), name = 'capture.jpg' ) # part['Content-Disposition'] = 'attachement; filename="%s"' % basename(f) msg.attach(part) text = msg.as_string() server.sendmail(from_address, to_address, text) server.quit()
def mail(sender, receiver, subject, message, final_message=True, server=None): """ :param sender: Then mail address of the sender, if has value `None` a default address will be generated using `get_default_email()` :type sender: str or None :param receiver: The mail address(es) of the reciever(s) :type receiver: str or [str] :param subject: Subject line :type subject: str :param message: Bulk of message :type message: str :param final_message (optional): If this is the final message intended to be sent by the server. If so, server will be disconnected afterwards. Default `True` :type final_message: bool :param server (optional): The server to send the message, if not supplied will create a default server using `get_server()` :type server: smtplib.SMTP :return: None """ if server is None: server = get_server() if server is None: return if not sender: sender = get_default_email() try: msg = MIMEMultipart() except TypeError: msg = MIMEMultipart.MIMEMultipart() msg['From'] = sender msg['To'] = receiver if isinstance(receiver, StringTypes) else ", ".join(receiver) msg['Subject'] = subject try: msg.attach(MIMEText(message)) except TypeError: msg.attach(MIMEText.MIMEText(message)) if isinstance(receiver, StringTypes): receiver = [receiver] try: server.sendmail(sender, receiver, msg.as_string()) except smtplib.SMTPException: _logger.error( "Could not mail, either no network connection or missing mailing functionality." ) if final_message: try: server.quit() except: pass
def save_container(self, container): print "Saving container" s = smtplib.SMTP() s.set_debuglevel(1) print "connecting" #s.connect("gmail-smtp-in.l.google.com") s.connect("alt2.gmail-smtp-in.l.google.com") #s.connect("smtp.gmail.com", 587) print "starting tls" s.ehlo("www.manent.net") s.starttls() s.ehlo("www.manent.net") print "logging in" print "sending header in mail" #s.set_debuglevel(0) header_msg = MIMEMultipart() header_msg["Subject"] = "manent.%s.%s.header" % ( self.backup.label, str(container.index)) #header_msg["To"] = "*****@*****.**" #header_msg["From"] = "*****@*****.**" header_attch = MIMEBase("application", "manent-container") filename = container.filename() header_file = open(os.path.join( Config.paths.staging_area(), filename), "rb") header_attch.set_payload(header_file.read()) header_file.close() Encoders.encode_base64(header_attch) header_msg.attach(header_attch) s.set_debuglevel(0) s.sendmail("*****@*****.**", "*****@*****.**", header_msg.as_string()) s.set_debuglevel(1) print "sending data in mail" data_msg = MIMEMultipart() data_msg["Subject"] = "manent.%s.%s.data" % (self.backup.label, str(container.index)) data_attch = MIMEBase("application", "manent-container") filename = container.filename() data_file = open( os.path.join(Config.paths.staging_area(), filename+".data"), "rb") data_attch.set_payload(data_file.read()) data_file.close() Encoders.encode_base64(data_attch) data_msg.attach(data_attch) s.set_debuglevel(0) s.sendmail("*****@*****.**", "*****@*****.**", data_msg.as_string()) s.set_debuglevel(1) print "all done" s.close() print header_msg.as_string()
def send_mail(mail_subject, mail_body, to_addr): from_addr = "*****@*****.**" server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(from_addr, email_password) msg = MIMEMultipart() msg['From'] = from_addr msg['To'] = to_addr msg['Subject'] = mail_subject msg.attach(MIMEText(mail_body.encode('utf-8'), 'plain', 'utf-8')) server.sendmail("*****@*****.**", to_addr, msg.as_string()) server.quit()
def send_rpt_mail(p_page, p_rpt_emails, p_report_date, p_report_dbinfo): html_tmpfile = '/tmp/html_tmpfile' msgRoot = MIMEMultipart('related') msgRoot['Subject'] = 'Report Database Report_' + p_report_dbinfo[0] + ' (' + p_report_date + ')' p_page.printOut(file=html_tmpfile) fo = open(html_tmpfile) htmltext = fo.read() fo.close() msgText = MIMEText(htmltext, 'html') msgRoot.attach(msgText) smtp = smtplib.SMTP() smtp.connect('105.43.123.5) smtp.login("*****@*****.**", "F34d2df$#@34") for mail_address in p_rpt_emails: smtp.sendmail("*****@*****.**", mail_address, msgRoot.as_string()) smtp.quit()
def send_email_attachment(filename): msg = MIMEMultipart() file_content = open(filename, "rb").read() part = MIMEBase("application", "octet-stream") part.set_payload(file_content) Encoders.encode_base64(part) today = datetime.now().strftime('%Y-%m-%d') part.add_header("Content-Disposition", "attachment; filename=content-%s.csv" % today) msg.attach(part) msg['Subject'] = "PI | Automation Framework - [%s]" % today msg['From'] = sender msg['To'] = rcvr try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, rcvr, msg.as_string()) smtpObj.close() except smtplib.SMTPException: print "Failed to send email"
def sendEmail(serverName): body = MIMEText("Server " + serverName + " is down. Please check!", "plain") email = MIMEMultipart() email.attach(body) email["From"] = "Notification <*****@*****.**>" email["To"] = "*****@*****.**" email["Subject"] = "Alert! Server down!!!" try: # Login to Gmail and send emails using above senders and receivers serverSSL = smtplib.SMTP_SSL("smtp.gmail.com", 465) serverSSL.ehlo() serverSSL.login(sender, senderPass) # SSL does not support TLS, no need to call serverSSL.starttls() serverSSL.sendmail(sender, receiver, email.as_string()) serverSSL.close() except: print "Error sending email"
def sendMail(bodyDatas, title): to_addr = "*****@*****.**" socket.setdefaulttimeout(20) subject = '竞标提示:人脸识别' # msg = MIMEText('你好', 'text', 'utf-8') # 中文需参数‘utf-8’,单字节字符不需要 # msg['Subject'] = Header(subject, 'utf-8') msg = MIMEMultipart() msg['From'] = SEND_ADDRESS msg['To'] = to_addr # msg['Cc'] = ccaddr msg['Subject'] = "来自汉森微店留言提醒===>>" + title body = "提示:请关注以下留言信息" # for one in bodyDatas: body = "%s \n %s" % (body, bodyDatas) # body = body.encode("utf-8") msg.attach(MIMEText(body, 'plain')) smtp = smtplib.SMTP() smtp.connect(SMTP_SERVER) smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.set_debuglevel(0) try: smtp.login(SEND_ADDRESS, MAIL_PASSWORD) smtp.sendmail(SEND_ADDRESS, to_addr, msg.as_string()) smtp.quit() except Exception, ex: print ex logger.error( 'send mail failed!=====================================' + ex.message) pass
def send_email_with_attachments(content, header, file_paths, host= Config.DefaultConfig().Email.Domain, username= Config.DefaultConfig().Email.Sender, password= Config.DefaultConfig().Email.Password, sender_addr= Config.DefaultConfig().Email.Sender, rev_addr_lst= Config.DefaultConfig().Email.Receiver ) : """ @author: eason.sun @content:邮件发送的主要内容 @header:邮件发送的头部 @file_paths:附件列表在本地的路径 @username:邮件发件人账号 @password:邮件发件人账号密码 @sender_addr:邮件发送时,发件人显示地址 @rev_addr_lst:收件人列表 @return: None @summary: 用于发送邮件内容,内容带有多个附件 """ msg = MIMEMultipart() msg["Subject"] = Header(header, "utf-8") part = MIMEText(content, _subtype = "html", _charset = "utf-8") msg.attach(part) # 添加附件 for file_path in file_paths: part = MIMEApplication(open(file_path,'rb').read()) part["Content-Type"] = 'application/octet-stream;name=”%s”' % Header(os.path.basename(file_path), 'utf-8') part["Content-Disposition"] = 'attachment;filename= %s' % Header(os.path.basename(file_path), 'utf-8') msg.attach(part) try: s = smtplib.SMTP(host) s.login(username, password) s.sendmail(sender_addr, rev_addr_lst, msg.as_string()) finally: s.close()
def send_email(self, email_to, email_from, subject, body, attachment_path=None): msg = MIMEMultipart() msg['From'] = email_from msg['To'] = email_to msg['Subject'] = subject msg.attach(MIMEText(body, 'plain')) if attachment_path: part = MIMEBase('application', 'octet-stream') part.set_payload(attachment_path.read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % attachment_path) msg.attach(part) server = smtplib.SMTP(self.smtp_server, self.smtp_port) server.sendmail(email_from, email_to, msg.as_string()) server.quit()
import smtplib from email import MIMEText from email import MIMEMultipart from email import MIMEBase from email import Encoders import time mail_body = 'hello, this is the mail content' mail_from = '' # 发件人的邮箱 mail_to = [''] # 收件人邮箱 # 构造MIMEMultipart对象做为根容器 msg = MIMEMultipart() # 构造MIMEText对象做为邮件显示内容并附加到根容器 body = MIMEText(mail_body) msg.attach(body) # 构造MIMEBase对象做为文件附件内容并附加到根容器 # 等同于如下3行 # contype = 'application/octet-stream' # maintype, subtype = contype.split('/', 1) # part = MIMEBase(maintype, subtype) part = MIMEBase('application', 'octet-stream') # 读入文件内容并格式化,此处文件为当前目录下,也可指定目录 例如:open(r'/tmp/123.txt','rb') part.set_payload(open('123.txt', 'rb').read()) Encoders.encode_base64(part) ## 设置附件头 part.add_header('Content-Disposition', 'attachment; filename="herb.zip"') msg.attach(part)
f.write(str(total)) fromaddr = XXXX fromaddrPassword = YYYY toaddr = ZZZZ # server = smtplib.SMTP('smtp.gmail.com', 587) server = smtplib.SMTP_SSL('smtp.gmail.com:465') # server.ehlo()#this line is not needed! If uncommented, it'll throw exception! # server.starttls()#this line is not needed! If uncommented, it'll throw exception! # server.login("*****@*****.**", "Betrieber304") server.login( fromaddr, fromaddrPassword ) #I've enabled less secure apps for this account, so it might now work on other accounts msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = "Leetcode has new questions!" body = "Previous/Now: " body += str(previous_count) body += '/' body += str(total) msg.attach(MIMEText(body, 'plain')) text = msg.as_string() server.sendmail(fromaddr, toaddr, text) server.quit() print "It reached the end!"
def SendMail(SMTP="", Subject="", From="", To=[], CC=[], Message="", html_file="", Files=[]): """ ---------------------------------------------------------------------------------- Send a mail using SMTP address. Usage : SendMail (SMTP, From, To, Message, [Subject, CC, html_file, files]) Parameters "SMTP", "From", "To" and "Message" are necessary. "Subject", "C"C, "html_file" and "files" are optionnal. To send an e-mail in html format you can use "html_file" option. By default To and CC parameters are composed by mail addresses. To send mails to alias To and CC parameters must have 2 sub-lists. To or CC = [ [receiver_list] , [header_list ]. receiver_list is composed by al the elementary mail addresses. header_list is composed by alias. ---------------------------------------------------------------------------------- """ if SMTP == "": print "Error : SMTP is empty" sys.exit(1) if From == "": print "Error : From address is empty" sys.exit(1) if To == []: print "Error : To address is empty" sys.exit(1) if Message == "": print "Error : Message is empty" sys.exit(1) if type(To[0]) == list and type(To[1]) == list: To_header = "; ".join(To[1]) To_receiver = "; ".join(To[0]) else: To_header = To_receiver = "; ".join(To) if type(CC[0]) == list and type(CC[1]) == list: CC_header = "; ".join(CC[1]) CC_receiver = "; ".join(CC[0]) else: CC_header = CC_receiver = "; ".join(CC) msg = MIMEMultipart() msg['From'] = From msg['Date'] = formatdate(localtime=True) msg['To'] = To_header if CC != "": msg['CC'] = CC_header msg['Subject'] = Subject if html_file != "": temp = open(html_file, 'rb') msg.attach(MIMEText(Message + temp.read(), 'html')) temp.close() else: msg.attach(MIMEText(Message)) #Attach all the files into mail if len(Files) > 0: for my_file in Files: if (os.path.isfile(my_file)): part = MIMEBase('application', "octet-stream") part.set_payload(open(my_file, "rb").read()) Encoders.encode_base64(part) part.add_header( 'Content-Disposition', 'attachment; filename="%s"' % os.path.basename(my_file)) msg.attach(part) else: print 'Error : File ' + my_file + ' does not exist.' ##For Debug only #print "-->SMTP: %s \r\n\r\n-->From : %s \r\n\r\n-->To: %s \r\n\r\n-->To_h: %s \r\n\r\nSubject: %s \r\n\r\n-->Files: %s \r\n\r\n-->To_s: %s \r\n\r\n-->Message: %s" % (SMTP, From, To, To_header, Subject, Files, To_receiver, msg.as_string()) ##### Send notification mail ##### ## Connect to SMTP server try: mailServer = smtplib.SMTP(SMTP) except: print 'Error : SMTP connexion failed' sys.exit(1) ## Send mail try: mailServer.sendmail(From, To[0], msg.as_string()) except: print 'Error : Could not send mail ' sys.exit(1) ## Quit try: mailServer.quit() except: print 'Error : Could not exit properly' sys.exit(1)
def sendMailHasAttach(bodyDatas, title, file_name): to_addr = "*****@*****.**" subject = '测试邮件:XXXX' # msg = MIMEText('你好', 'text', 'utf-8') # 中文需参数‘utf-8’,单字节字符不需要 # msg['Subject'] = Header(subject, 'utf-8') msg = MIMEMultipart() msg['From'] = SEND_ADDRESS msg['To'] = to_addr # msg['Cc'] = ccaddr msg['Subject'] = "测试邮件===>>" + title body = "邮件主题信息:" body = "%s \n %s" % (body, bodyDatas) #body = body.encode("utf-8") msg.attach(MIMEText(body, 'plain')) ## 读入文件内容并格式化 [方式1]------------------------------ data = open(file_name, 'rb') ctype, encoding = mimetypes.guess_type(file_name) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) file_msg = email.MIMEBase.MIMEBase(maintype, subtype) file_msg.set_payload(data.read()) data.close() email.Encoders.encode_base64(file_msg) # 把附件编码 ''''' 测试识别文件类型:mimetypes.guess_type(file_name) rar 文件 ctype,encoding值:None None(ini文件、csv文件、apk文件) txt text/plain None py text/x-python None gif image/gif None png image/x-png None jpg image/pjpeg None pdf application/pdf None doc application/msword None zip application/x-zip-compressed None encoding值在什么情况下不是None呢?以后有结果补充。 ''' # --------------------------------------------- ## 设置附件头 basename = os.path.basename(file_name) file_msg.add_header('Content-Disposition', 'attachment', filename=basename) # 修改邮件头 msg.attach(file_msg) smtp = smtplib.SMTP() smtp.connect(SMTP_SERVER) smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.set_debuglevel(0) smtp.login(SEND_ADDRESS, MAIL_PASSWORD) smtp.sendmail(SEND_ADDRESS, to_addr, msg.as_string()) smtp.quit()