python email模塊的使用實例

在使用python過程中,需要用的email模塊來進行郵件的發送和接收,包含自定義郵件的中文、主題、日期、附件等信息,以下是我使用email模塊來發送一個測試報告相關信息的郵件的例子:

#!/usr/bin/python  # -*- coding: utf-8 -*-  '''  @author:freesigefei  Created on 2016年3月20日  Updated on 2016年5月4日  '''  #------------------------------------------------------------------------------------------------  import smtplib  from email.mime.text import MIMEText  from email.mime.multipart import MIMEMultipart  from email.header import Header  import os,time,re    def send_Test_email(mail_to):      '''本模塊實現獲取最新的測試報告html文件,讀取部分報告內容作為郵件正文,將報告作為附件,並發送到指定的郵箱,          參數mail_to代表的是接收郵箱,例如:'[email protected]' '''        #發送郵箱      mail_from = '[email protected]'      #發送郵件主題      mail_subject = 'Automation Test Report'      #發送郵箱服務器      mail_smtpserver = 'smtp.sina.com'      #發送郵箱用戶/密碼      mail_username = '[email protected]'      mail_password = 'yyyyyy'        #定義郵件內容,中文需參數『utf-8』,單位元組字符不需要      '''      #發送文件形式的郵件      msg = MIMEText('你好!','text','utf-8')      '''      '''      #發送html形式以正常文本顯示在郵件內容中的郵件      msg = MIMEText('<html><h1>你好!</h1></html>','html','utf-8')      '''      '''      #讀取html文件內容並發送      f=open(file_new,'rb')      mail_body=f.read()      f.close()      print mail_body      msg=MIMEText(mail_body,_subtype='html',_charset='utf-8')      '''        #創建一個帶附件的郵件實例(內容)      msg = MIMEMultipart()      #找到report目錄下最新生成的報告文件供後續使用      result_dir = 'D:\report'      lists=os.listdir(result_dir)      lists.sort(key=lambda fn: os.path.getmtime(result_dir+"\"+fn) if not                 os.path.isdir(result_dir+"\"+fn) else 0)      print (u'The Latest Test Report is: '+lists[-1])      file_new = os.path.join(result_dir,lists[-1])      #讀取最新的測試報告文件獲取部分信息來定義郵件的內容      Regex_Theme=re.compile(r'Automation Test Report')      Regex_Content=re.compile(r'<strong>(.*:)</strong>(.*)<')      Report_File=open(file_new,'r')      Mail_Content=[]      for line in Report_File.readlines():          if '<title>Automation Test Report</title>' in line or "<p class='attribute'>" in line:              i=Regex_Theme.findall(line)              j=Regex_Content.findall(line)              if i != []:                  Mail_Content.append(i)              if j != []:                  Mail_Content.append(j)      Report_File.close()      #將讀取到的測試報告的數據以html形式顯示為郵件的中文      msgTest=MIMEText('''<html><h1>Test completed,Test results are as follows:</h1></html>'''                       '''<hr />'''                       '''<p><strong>'''+Mail_Content[0][0]+'''</strong></p>'''                       '''<p><strong>'''+Mail_Content[1][0][0]+'''</strong>'''+Mail_Content[1][0][1]+'''</p>'''                       '''<p><strong>'''+Mail_Content[2][0][0]+'''</strong>'''+Mail_Content[2][0][1]+'''</p>'''                       '''<p><strong>'''+Mail_Content[3][0][0]+'''</strong>'''+Mail_Content[3][0][1]+'''</p>'''                       '''<hr />'''                       '''<p>PS: Detailed test results please refer to the attachment</p>'''                       ,'html','utf-8')      msg.attach(msgTest)      #定義郵件的附件      att1 = MIMEText(open(file_new, 'rb').read(), 'base64', 'utf-8')      att1["Content-Type"] = 'application/octet-stream'      att1["Content-Disposition"] ='attachment; filename="Automation test report.html"'#這裡的filename指的是附件的名稱及類型      msg.attach(att1)      #將郵件的主題等相關信息添加到郵件實例      msg['Subject'] = Header(mail_subject)      msg['From'] = mail_from      msg['To'] = mail_to      msg['date']=time.strftime('%a, %d %b %Y %H:%M:%S %z')      #創建發送服務器實例並將發送服務器添加到實例中      smtp = smtplib.SMTP()      smtp.connect(mail_smtpserver)      '''      #採用ssl加密傳輸      smtp.ehlo()      smtp.starttls()      smtp.ehlo()      '''      '''      #打印交互的日誌信息      #smtp.set_debuglevel(1)      '''      #登錄發送郵件服務器並進行郵件的發送      smtp.login(mail_username, mail_password)      smtp.sendmail(mail_from, mail_to, msg.as_string())      print u'Test report sent successfully,Please go to the following email to check the test report :%s' %mail_to      smtp.quit()    #----------------------------------------------------------------------------------------------------  if __name__ == "__main__":      send_Test_email('[email protected]')

當然,如果要使用email模塊的其他功能,可以參考網上的以下7個列子:

一,文件形式的郵件

#!/usr/bin/env python3  #coding: utf-8  import smtplib  from email.mime.text import MIMEText  from email.header import Header    sender = '***'  receiver = '***'  subject = 'python email test'  smtpserver = 'smtp.163.com'  username = '***'  password = '***'    msg = MIMEText('你好','text','utf-8')#中文需參數『utf-8',單位元組字符不需要  msg['Subject'] = Header(subject, 'utf-8')    smtp = smtplib.SMTP()  smtp.connect('smtp.163.com')  smtp.login(username, password)  smtp.sendmail(sender, receiver, msg.as_string())  smtp.quit()

二、html形式的郵件

#!/usr/bin/env python3  #coding: utf-8  import smtplib  from email.mime.text import MIMEText    sender = '***'  receiver = '***'  subject = 'python email test'  smtpserver = 'smtp.163.com'  username = '***'  password = '***'    msg = MIMEText('</pre>  <h1>你好</h1>  <pre>','html','utf-8')    msg['Subject'] = subject    smtp = smtplib.SMTP()  smtp.connect('smtp.163.com')  smtp.login(username, password)  smtp.sendmail(sender, receiver, msg.as_string())  smtp.quit()

三、帶圖片的html郵件

#!/usr/bin/env python3  #coding: utf-8  import smtplib  from email.mime.multipart import MIMEMultipart  from email.mime.text import MIMEText  from email.mime.image import MIMEImage    sender = '***'  receiver = '***'  subject = 'python email test'  smtpserver = 'smtp.163.com'  username = '***'  password = '***'    msgRoot = MIMEMultipart('related')  msgRoot['Subject'] = 'test message'    msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.  <img alt="" src="cid:image1" />  good!','html','utf-8')  msgRoot.attach(msgText)    fp = open('h:\python\1.jpg', 'rb')  msgImage = MIMEImage(fp.read())  fp.close()    msgImage.add_header('Content-ID', '')  msgRoot.attach(msgImage)    smtp = smtplib.SMTP()  smtp.connect('smtp.163.com')  smtp.login(username, password)  smtp.sendmail(sender, receiver, msgRoot.as_string())  smtp.quit()

四、帶附件的郵件

#!/usr/bin/env python3  #coding: utf-8  import smtplib  from email.mime.multipart import MIMEMultipart  from email.mime.text import MIMEText  from email.mime.image import MIMEImage    sender = '***'  receiver = '***'  subject = 'python email test'  smtpserver = 'smtp.163.com'  username = '***'  password = '***'    msgRoot = MIMEMultipart('related')  msgRoot['Subject'] = 'test message'    #構造附件  att = MIMEText(open('h:\python\1.jpg', 'rb').read(), 'base64', 'utf-8')  att["Content-Type"] = 'application/octet-stream'  att["Content-Disposition"] = 'attachment; filename="1.jpg"'  msgRoot.attach(att)    smtp = smtplib.SMTP()  smtp.connect('smtp.163.com')  smtp.login(username, password)  smtp.sendmail(sender, receiver, msgRoot.as_string())  smtp.quit()

五、群郵件

#!/usr/bin/env python3  #coding: utf-8  import smtplib  from email.mime.text import MIMEText    sender = '***'  receiver = ['***','****',……]  subject = 'python email test'  smtpserver = 'smtp.163.com'  username = '***'  password = '***'    msg = MIMEText('你好','text','utf-8')    msg['Subject'] = subject    smtp = smtplib.SMTP()  smtp.connect('smtp.163.com')  smtp.login(username, password)  smtp.sendmail(sender, receiver, msg.as_string())  smtp.quit()

六、包含各種元素的郵件

#!/usr/bin/env python3  #coding: utf-8  import smtplib  from email.mime.multipart import MIMEMultipart  from email.mime.text import MIMEText  from email.mime.image import MIMEImage    sender = '***'  receiver = '***'  subject = 'python email test'  smtpserver = 'smtp.163.com'  username = '***'  password = '***'    # Create message container - the correct MIME type is multipart/alternative.  msg = MIMEMultipart('alternative')  msg['Subject'] = "Link"    # Create the body of the message (a plain-text and an HTML version).  text = "Hi!nHow are you?nHere is the link you wanted:nhttp://www.python.org"  html = """       Hi!           How are you?           Here is the <a href="http://www.python.org">link</a> you wanted.         """    # Record the MIME types of both parts - text/plain and text/html.  part1 = MIMEText(text, 'plain')  part2 = MIMEText(html, 'html')    # Attach parts into message container.  # According to RFC 2046, the last part of a multipart message, in this case  # the HTML message, is best and preferred.  msg.attach(part1)  msg.attach(part2)  #構造附件  att = MIMEText(open('h:\python\1.jpg', 'rb').read(), 'base64', 'utf-8')  att["Content-Type"] = 'application/octet-stream'  att["Content-Disposition"] = 'attachment; filename="1.jpg"'  msg.attach(att)    smtp = smtplib.SMTP()  smtp.connect('smtp.163.com')  smtp.login(username, password)  smtp.sendmail(sender, receiver, msg.as_string())  smtp.quit()

7、基於ssl的郵件

#!/usr/bin/env python3  #coding: utf-8  import smtplib  from email.mime.text import MIMEText  from email.header import Header  sender = '***'  receiver = '***'  subject = 'python email test'  smtpserver = 'smtp.163.com'  username = '***'  password = '***'    msg = MIMEText('你好','text','utf-8')#中文需參數『utf-8',單位元組字符不需要  msg['Subject'] = Header(subject, 'utf-8')    smtp = smtplib.SMTP()  smtp.connect('smtp.163.com')  smtp.ehlo()  smtp.starttls()  smtp.ehlo()  smtp.set_debuglevel(1)  smtp.login(username, password)  smtp.sendmail(sender, receiver, msg.as_string())  smtp.quit()