python email模块的使用实例

在使用python过程中,需要用的email模块来进行邮件的发送和接收,包含自定义邮件的中文、主题、日期、附件等信息,以下是我使用email模块来发送一个测试报告相关信息的邮件的例子:

[python] view plain copy
print ?
  1. #!/usr/bin/python  
  2. # -*- coding: utf-8 -*-  
  3. ''''' 
  4. @author:freesigefei 
  5. Created on 2016年3月20日 
  6. Updated on 2016年5月4日 
  7. '''  
  8. #------------------------------------------------------------------------------------------------  
  9. import smtplib  
  10. from email.mime.text import MIMEText  
  11. from email.mime.multipart import MIMEMultipart  
  12. from email.header import Header  
  13. import os,time,re  
  14.   
  15. def send_Test_email(mail_to):  
  16.     '''''本模块实现获取最新的测试报告html文件,读取部分报告内容作为邮件正文,将报告作为附件,并发送到指定的邮箱, 
  17.         参数mail_to代表的是接收邮箱,例如:'[email protected]' '''  
  18.       
  19.     #发送邮箱  
  20.     mail_from = '[email protected]'  
  21.     #发送邮件主题  
  22.     mail_subject = 'Automation Test Report'  
  23.     #发送邮箱服务器  
  24.     mail_smtpserver = 'smtp.sina.com'  
  25.     #发送邮箱用户/密码  
  26.     mail_username = '[email protected]'  
  27.     mail_password = 'yyyyyy'  
  28.   
  29.     #定义邮件内容,中文需参数‘utf-8’,单字节字符不需要  
  30.     ''''' 
  31.     #发送文件形式的邮件 
  32.     msg = MIMEText('你好!','text','utf-8') 
  33.     '''  
  34.     ''''' 
  35.     #发送html形式以正常文本显示在邮件内容中的邮件 
  36.     msg = MIMEText('<html><h1>你好!</h1></html>','html','utf-8') 
  37.     '''  
  38.     ''''' 
  39.     #读取html文件内容并发送 
  40.     f=open(file_new,'rb') 
  41.     mail_body=f.read() 
  42.     f.close() 
  43.     print mail_body 
  44.     msg=MIMEText(mail_body,_subtype='html',_charset='utf-8') 
  45.     '''  
  46.       
  47.     #创建一个带附件的邮件实例(内容)  
  48.     msg = MIMEMultipart()  
  49.     #找到report目录下最新生成的报告文件供后续使用  
  50.     result_dir = 'D:\\report'  
  51.     lists=os.listdir(result_dir)  
  52.     lists.sort(key=lambda fn: os.path.getmtime(result_dir+"\\"+fn) if not  
  53.                os.path.isdir(result_dir+"\\"+fn) else 0)  
  54.     print (u'The Latest Test Report is: '+lists[-1])  
  55.     file_new = os.path.join(result_dir,lists[-1])  
  56.     #读取最新的测试报告文件获取部分信息来定义邮件的内容  
  57.     Regex_Theme=re.compile(r'Automation Test Report')  
  58.     Regex_Content=re.compile(r'<strong>(.*:)</strong>(.*)<')  
  59.     Report_File=open(file_new,'r')  
  60.     Mail_Content=[]  
  61.     for line in Report_File.readlines():  
  62.         if '<title>Automation Test Report</title>' in line or "<p class='attribute'>" in line:  
  63.             i=Regex_Theme.findall(line)  
  64.             j=Regex_Content.findall(line)  
  65.             if i != []:  
  66.                 Mail_Content.append(i)  
  67.             if j != []:  
  68.                 Mail_Content.append(j)  
  69.     Report_File.close()  
  70.     #将读取到的测试报告的数据以html形式显示为邮件的中文  
  71.     msgTest=MIMEText('''''<html><h1>Test completed,Test results are as follows:</h1></html>'''  
  72.                      '''''<hr />'''  
  73.                      '''''<p><strong>'''+Mail_Content[0][0]+'''''</strong></p>'''  
  74.                      '''''<p><strong>'''+Mail_Content[1][0][0]+'''''</strong>'''+Mail_Content[1][0][1]+'''''</p>'''  
  75.                      '''''<p><strong>'''+Mail_Content[2][0][0]+'''''</strong>'''+Mail_Content[2][0][1]+'''''</p>'''  
  76.                      '''''<p><strong>'''+Mail_Content[3][0][0]+'''''</strong>'''+Mail_Content[3][0][1]+'''''</p>'''  
  77.                      '''''<hr />'''  
  78.                      '''''<p>PS: Detailed test results please refer to the attachment</p>'''  
  79.                      ,'html','utf-8')  
  80.     msg.attach(msgTest)  
  81.     #定义邮件的附件  
  82.     att1 = MIMEText(open(file_new, 'rb').read(), 'base64''utf-8')  
  83.     att1["Content-Type"] = 'application/octet-stream'  
  84.     att1["Content-Disposition"] ='attachment; filename="Automation test report.html"'#这里的filename指的是附件的名称及类型  
  85.     msg.attach(att1)  
  86.     #将邮件的主题等相关信息添加到邮件实例  
  87.     msg['Subject'] = Header(mail_subject)  
  88.     msg['From'] = mail_from  
  89.     msg['To'] = mail_to  
  90.     msg['date']=time.strftime('%a, %d %b %Y %H:%M:%S %z')   
  91.     #创建发送服务器实例并将发送服务器添加到实例中  
  92.     smtp = smtplib.SMTP()  
  93.     smtp.connect(mail_smtpserver)  
  94.     ''''' 
  95.     #采用ssl加密传输 
  96.     smtp.ehlo() 
  97.     smtp.starttls() 
  98.     smtp.ehlo() 
  99.     '''  
  100.     ''''' 
  101.     #打印交互的日志信息 
  102.     #smtp.set_debuglevel(1) 
  103.     '''  
  104.     #登录发送邮件服务器并进行邮件的发送  
  105.     smtp.login(mail_username, mail_password)  
  106.     smtp.sendmail(mail_from, mail_to, msg.as_string())  
  107.     print u'Test report sent successfully,Please go to the following email to check the test report :%s' %mail_to  
  108.     smtp.quit()  
  109.       
  110. #----------------------------------------------------------------------------------------------------  
  111. if __name__ == "__main__":  
  112.     send_Test_email('[email protected]')  
#!/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个列子:

一,文件形式的邮件

[python] view plain copy
print ?
  1. #!/usr/bin/env python3  
  2. #coding: utf-8  
  3. import smtplib  
  4. from email.mime.text import MIMEText  
  5. from email.header import Header  
  6.   
  7. sender = '***'  
  8. receiver = '***'  
  9. subject = 'python email test'  
  10. smtpserver = 'smtp.163.com'  
  11. username = '***'  
  12. password = '***'  
  13.   
  14. msg = MIMEText('你好','text','utf-8')#中文需参数‘utf-8',单字节字符不需要  
  15. msg['Subject'] = Header(subject, 'utf-8')  
  16.   
  17. smtp = smtplib.SMTP()  
  18. smtp.connect('smtp.163.com')  
  19. smtp.login(username, password)  
  20. smtp.sendmail(sender, receiver, msg.as_string())  
  21. smtp.quit()  
#!/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形式的邮件

[python] view plain copy
print ?
  1. #!/usr/bin/env python3  
  2. #coding: utf-8  
  3. import smtplib  
  4. from email.mime.text import MIMEText  
  5.   
  6. sender = '***'  
  7. receiver = '***'  
  8. subject = 'python email test'  
  9. smtpserver = 'smtp.163.com'  
  10. username = '***'  
  11. password = '***'  
  12.   
  13. msg = MIMEText('</pre>  
  14. <h1>你好</h1>  
  15. <pre>','html','utf-8')   
  16.   
  17. msg['Subject'] = subject   
  18.   
  19. smtp = smtplib.SMTP()  
  20. smtp.connect('smtp.163.com')  
  21. smtp.login(username, password)  
  22. smtp.sendmail(sender, receiver, msg.as_string())  
  23. 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('</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邮件

[python] view plain copy
print ?
  1. #!/usr/bin/env python3  
  2. #coding: utf-8  
  3. import smtplib  
  4. from email.mime.multipart import MIMEMultipart  
  5. from email.mime.text import MIMEText  
  6. from email.mime.image import MIMEImage   
  7.   
  8. sender = '***'  
  9. receiver = '***'  
  10. subject = 'python email test'  
  11. smtpserver = 'smtp.163.com'  
  12. username = '***'  
  13. password = '***'   
  14.   
  15. msgRoot = MIMEMultipart('related')  
  16. msgRoot['Subject'] = 'test message'   
  17.   
  18. msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.  
  19. <img alt="" src="cid:image1" />  
  20. good!','html','utf-8')  
  21. msgRoot.attach(msgText)   
  22.   
  23. fp = open('h:\\python\\1.jpg''rb')  
  24. msgImage = MIMEImage(fp.read())  
  25. fp.close()   
  26.   
  27. msgImage.add_header('Content-ID''')  
  28. msgRoot.attach(msgImage)   
  29.   
  30. smtp = smtplib.SMTP()  
  31. smtp.connect('smtp.163.com')  
  32. smtp.login(username, password)  
  33. smtp.sendmail(sender, receiver, msgRoot.as_string())  
  34. 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' 

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()


四、带附件的邮件

[python] view plain copy
print ?
  1. #!/usr/bin/env python3  
  2. #coding: utf-8  
  3. import smtplib  
  4. from email.mime.multipart import MIMEMultipart  
  5. from email.mime.text import MIMEText  
  6. from email.mime.image import MIMEImage   
  7.   
  8. sender = '***'  
  9. receiver = '***'  
  10. subject = 'python email test'  
  11. smtpserver = 'smtp.163.com'  
  12. username = '***'  
  13. password = '***'   
  14.   
  15. msgRoot = MIMEMultipart('related')  
  16. msgRoot['Subject'] = 'test message'   
  17.   
  18. #构造附件  
  19. att = MIMEText(open('h:\\python\\1.jpg''rb').read(), 'base64''utf-8')  
  20. att["Content-Type"] = 'application/octet-stream'  
  21. att["Content-Disposition"] = 'attachment; filename="1.jpg"'  
  22. msgRoot.attach(att)   
  23.   
  24. smtp = smtplib.SMTP()  
  25. smtp.connect('smtp.163.com')  
  26. smtp.login(username, password)  
  27. smtp.sendmail(sender, receiver, msgRoot.as_string())  
  28. 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()


五、群邮件

[python] view plain copy
print ?
  1. #!/usr/bin/env python3  
  2. #coding: utf-8  
  3. import smtplib  
  4. from email.mime.text import MIMEText   
  5.   
  6. sender = '***'  
  7. receiver = ['***','****',……]  
  8. subject = 'python email test'  
  9. smtpserver = 'smtp.163.com'  
  10. username = '***'  
  11. password = '***'   
  12.   
  13. msg = MIMEText('你好','text','utf-8')   
  14.   
  15. msg['Subject'] = subject   
  16.   
  17. smtp = smtplib.SMTP()  
  18. smtp.connect('smtp.163.com')  
  19. smtp.login(username, password)  
  20. smtp.sendmail(sender, receiver, msg.as_string())  
  21. 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()


六、包含各种元素的邮件

[python] view plain copy
print ?
  1. #!/usr/bin/env python3  
  2. #coding: utf-8  
  3. import smtplib  
  4. from email.mime.multipart import MIMEMultipart  
  5. from email.mime.text import MIMEText  
  6. from email.mime.image import MIMEImage   
  7.   
  8. sender = '***'  
  9. receiver = '***'  
  10. subject = 'python email test'  
  11. smtpserver = 'smtp.163.com'  
  12. username = '***'  
  13. password = '***'   
  14.   
  15. # Create message container - the correct MIME type is multipart/alternative.  
  16. msg = MIMEMultipart('alternative')  
  17. msg['Subject'] = "Link"   
  18.   
  19. # Create the body of the message (a plain-text and an HTML version).  
  20. text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"  
  21. html = """\ 
  22.  
  23.   
  24. Hi! 
  25.  
  26.        How are you? 
  27.  
  28.        Here is the <a href="http://www.python.org">link</a> you wanted. 
  29.  
  30.   
  31.  
  32. """   
  33.   
  34. # Record the MIME types of both parts - text/plain and text/html.  
  35. part1 = MIMEText(text, 'plain')  
  36. part2 = MIMEText(html, 'html')   
  37.   
  38. # Attach parts into message container.  
  39. # According to RFC 2046, the last part of a multipart message, in this case  
  40. # the HTML message, is best and preferred.  
  41. msg.attach(part1)  
  42. msg.attach(part2)  
  43. #构造附件  
  44. att = MIMEText(open('h:\\python\\1.jpg''rb').read(), 'base64''utf-8')  
  45. att["Content-Type"] = 'application/octet-stream'  
  46. att["Content-Disposition"] = 'attachment; filename="1.jpg"'  
  47. msg.attach(att)   
  48.   
  49. smtp = smtplib.SMTP()  
  50. smtp.connect('smtp.163.com')  
  51. smtp.login(username, password)  
  52. smtp.sendmail(sender, receiver, msg.as_string())  
  53. 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的邮件

[python] view plain copy
print ?
  1. #!/usr/bin/env python3  
  2. #coding: utf-8  
  3. import smtplib  
  4. from email.mime.text import MIMEText  
  5. from email.header import Header  
  6. sender = '***'  
  7. receiver = '***'  
  8. subject = 'python email test'  
  9. smtpserver = 'smtp.163.com'  
  10. username = '***'  
  11. password = '***'   
  12.   
  13. msg = MIMEText('你好','text','utf-8')#中文需参数‘utf-8',单字节字符不需要  
  14. msg['Subject'] = Header(subject, 'utf-8')   
  15.   
  16. smtp = smtplib.SMTP()  
  17. smtp.connect('smtp.163.com')  
  18. smtp.ehlo()  
  19. smtp.starttls()  
  20. smtp.ehlo()  
  21. smtp.set_debuglevel(1)  
  22. smtp.login(username, password)  
  23. smtp.sendmail(sender, receiver, msg.as_string())  
  24. smtp.quit()  
#!/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()



猜你喜欢

转载自www.cnblogs.com/args/p/9133652.html