python自動發郵件總結及實例說明

python自動發郵件總結及實例說明

python發郵件需要掌握兩個模塊的用法,smtplib和email,這倆模塊是python自帶的,只需import即可使用。smtplib模塊主要負責發送郵件,email模塊主要負責構造郵件。

smtplib模塊主要負責發送郵件:是一個發送郵件的動作,連接郵箱服務器,登錄郵箱,發送郵件(有發件人,收信人,郵件內容)。

email模塊主要負責構造郵件:指的是郵箱頁面顯示的一些構造,如發件人,收件人,主題,正文,附件等。

 

1.smtplib模塊

smtplib使用較爲簡單。以下是最基本的語法。

導入及使用方法如下:

複製代碼

import smtplib

smtp = smtplib.SMTP() 
smtp.connect('smtp.163.com,25') 
smtp.login(username, password) 
smtp.sendmail(sender, receiver, msg.as_string()) 
smtp.quit()

複製代碼

說明:

smtplib.SMTP():實例化SMTP()

connect(host,port):

host:指定連接的郵箱服務器。常用郵箱的smtp服務器地址如下:

新浪郵箱:smtp.sina.com,新浪VIP:smtp.vip.sina.com,搜狐郵箱:smtp.sohu.com,126郵箱:smtp.126.com,139郵箱:smtp.139.com,163網易郵箱:smtp.163.com。

port:指定連接服務器的端口號,默認爲25.

login(user,password):

user:登錄郵箱的用戶名。

password:登錄郵箱的密碼,像筆者用的是網易郵箱,網易郵箱一般是網頁版,需要用到客戶端密碼,需要在網頁版的網易郵箱中設置授權碼,該授權碼即爲客戶端密碼。

sendmail(from_addr,to_addrs,msg,...):

from_addr:郵件發送者地址

to_addrs:郵件接收者地址。字符串列表['接收地址1','接收地址2','接收地址3',...]或'接收地址'

msg:發送消息:郵件內容。一般是msg.as_string():as_string()是將msg(MIMEText對象或者MIMEMultipart對象)變爲str。

quit():用於結束SMTP會話。

 

2.email模塊

email模塊下有mime包,mime英文全稱爲“Multipurpose Internet Mail Extensions”,即多用途互聯網郵件擴展,是目前互聯網電子郵件普遍遵循的郵件技術規範。

該mime包下常用的有三個模塊:text,image,multpart

導入方法如下:

from email.mime.multipart import MIMEMultipart    
from email.mime.text import MIMEText    
from email.mime.image import MIMEImage

構造一個郵件對象就是一個Message對象,如果構造一個MIMEText對象,就表示一個文本郵件對象,如果構造一個MIMEImage對象,就表示一個作爲附件的圖片,要把多個對象組合起來,就用MIMEMultipart對象,而MIMEBase可以表示任何對象。它們的繼承關係如下:

Message
+- MIMEBase
   +- MIMEMultipart
   +- MIMENonMultipart
      +- MIMEMessage
      +- MIMEText
      +- MIMEImage

2.1 text說明

郵件發送程序爲了防止有些郵件閱讀軟件不能顯示處理HTML格式的數據,通常都會用兩類型分別爲"text/plain"和"text/html"

構造MIMEText對象時,第一個參數是郵件正文,第二個參數是MIME的subtype,最後一定要用utf-8編碼保證多語言兼容性。

2.1.1添加普通文本

text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.baidu.com"    
text_plain = MIMEText(text,'plain', 'utf-8')    

查看MIMEText屬性:可以觀察到MIMEText,MIMEImage和MIMEMultipart的屬性都一樣。

print dir(text_plain)

['__contains__', '__delitem__', '__doc__', '__getitem__', '__init__', '__len__', '__module__', '__setitem__', '__str__', '_charset', '_default_type', '_get_params_preserve', '_headers', '_payload', '_unixfrom', 'add_header', 'as_string', 'attach', 'defects', 'del_param', 'epilogue', 'get', 'get_all', 'get_boundary', 'get_charset', 'get_charsets', 'get_content_charset', 'get_content_maintype', 'get_content_subtype', 'get_content_type', 'get_default_type', 'get_filename', 'get_param', 'get_params', 'get_payload', 'get_unixfrom', 'has_key', 'is_multipart', 'items', 'keys', 'preamble', 'replace_header', 'set_boundary', 'set_charset', 'set_default_type', 'set_param', 'set_payload', 'set_type', 'set_unixfrom', 'values', 'walk']

2.1.2添加超文本

複製代碼

html = """
<html>  
  <body>  
    <p> 
       Here is the <a href="http://www.baidu.com">link</a> you wanted.
    </p> 
  </body>  
</html>  
"""    
text_html = MIMEText(html,'html', 'utf-8')  

複製代碼

2.1.3添加附件

sendfile=open(r'D:\pythontest\1111.txt','rb').read()
text_att = MIMEText(sendfile, 'base64', 'utf-8')    
text_att["Content-Type"] = 'application/octet-stream'    
text_att["Content-Disposition"] = 'attachment; filename="顯示的名字.txt"'  

 

2.2 image說明

添加圖片:

sendimagefile=open(r'D:\pythontest\testimage.png','rb').read()
image = MIMEImage(sendimagefile)
image.add_header('Content-ID','<image1>')

查看MIMEImage屬性:

print dir(image)

['__contains__', '__delitem__', '__doc__', '__getitem__', '__init__', '__len__', '__module__', '__setitem__', '__str__', '_charset', '_default_type', '_get_params_preserve', '_headers', '_payload', '_unixfrom', 'add_header', 'as_string', 'attach', 'defects', 'del_param', 'epilogue', 'get', 'get_all', 'get_boundary', 'get_charset', 'get_charsets', 'get_content_charset', 'get_content_maintype', 'get_content_subtype', 'get_content_type', 'get_default_type', 'get_filename', 'get_param', 'get_params', 'get_payload', 'get_unixfrom', 'has_key', 'is_multipart', 'items', 'keys', 'preamble', 'replace_header', 'set_boundary', 'set_charset', 'set_default_type', 'set_param', 'set_payload', 'set_type', 'set_unixfrom', 'values', 'walk']

 

2.3 multpart說明

常見的multipart類型有三種:multipart/alternative, multipart/related和multipart/mixed。

郵件類型爲"multipart/alternative"的郵件包括純文本正文(text/plain)和超文本正文(text/html)。

郵件類型爲"multipart/related"的郵件正文中包括圖片,聲音等內嵌資源。

郵件類型爲"multipart/mixed"的郵件包含附件。向上兼容,如果一個郵件有純文本正文,超文本正文,內嵌資源,附件,則選擇mixed類型。

msg = MIMEMultipart('mixed')

我們必須把Subject,From,To,Date添加到MIMEText對象或者MIMEMultipart對象中,郵件中才會顯示主題,發件人,收件人,時間(若無時間,就默認一般爲當前時間,該值一般不設置)。

msg = MIMEMultipart('mixed') 
msg['Subject'] = 'Python email test'
msg['From'] = '[email protected] <[email protected]>'
msg['To'] = '[email protected]'
msg['Date']='2012-3-16'

查看MIMEMultipart屬性:

msg = MIMEMultipart('mixed') 
print dir(msg) 

結果:

['__contains__', '__delitem__', '__doc__', '__getitem__', '__init__', '__len__', '__module__', '__setitem__', '__str__', '_charset', '_default_type', '_get_params_preserve', '_headers', '_payload', '_unixfrom', 'add_header', 'as_string', 'attach', 'defects', 'del_param', 'epilogue', 'get', 'get_all', 'get_boundary', 'get_charset', 'get_charsets', 'get_content_charset', 'get_content_maintype', 'get_content_subtype', 'get_content_type', 'get_default_type', 'get_filename', 'get_param', 'get_params', 'get_payload', 'get_unixfrom', 'has_key', 'is_multipart', 'items', 'keys', 'preamble', 'replace_header', 'set_boundary', 'set_charset', 'set_default_type', 'set_param', 'set_payload', 'set_type', 'set_unixfrom', 'values', 'walk']

說明:

msg.add_header(_name,_value,**_params):添加郵件頭字段。

msg.as_string():是將msg(MIMEText對象或者MIMEMultipart對象)變爲str,如果只有一個html超文本正文或者plain普通文本正文的話,一般msg的類型可以是MIMEText;如果是多個的話,就都添加到MIMEMultipart,msg類型就變爲MIMEMultipart。

msg.attach(MIMEText對象或MIMEImage對象):將MIMEText對象或MIMEImage對象添加到MIMEMultipart對象中。MIMEMultipart對象代表郵件本身,MIMEText對象或MIMEImage對象代表郵件正文。

以上的構造的文本,超文本,附件,圖片都何以添加到MIMEMultipart('mixed')中:

msg.attach(text_plain)    
msg.attach(text_html)    
msg.attach(text_att)    
msg.attach(image)

 

3.文字,html,圖片,附件實現實例

複製代碼

#coding: utf-8    
  
import smtplib    
from email.mime.multipart import MIMEMultipart    
from email.mime.text import MIMEText    
from email.mime.image import MIMEImage 
from email.header import Header   
    
#設置smtplib所需的參數
#下面的發件人,收件人是用於郵件傳輸的。
smtpserver = 'smtp.163.com'
username = '[email protected]'
password='XXX'
sender='[email protected]'
#receiver='[email protected]'
#收件人爲多個收件人
receiver=['[email protected]','[email protected]']

subject = 'Python email test'
#通過Header對象編碼的文本,包含utf-8編碼信息和Base64編碼信息。以下中文名測試ok
#subject = '中文標題'
#subject=Header(subject, 'utf-8').encode()
    
#構造郵件對象MIMEMultipart對象
#下面的主題,發件人,收件人,日期是顯示在郵件頁面上的。
msg = MIMEMultipart('mixed') 
msg['Subject'] = subject
msg['From'] = '[email protected] <[email protected]>'
#msg['To'] = '[email protected]'
#收件人爲多個收件人,通過join將列表轉換爲以;爲間隔的字符串
msg['To'] = ";".join(receiver) 
#msg['Date']='2012-3-16'

#構造文字內容   
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.baidu.com"    
text_plain = MIMEText(text,'plain', 'utf-8')    
msg.attach(text_plain)    

#構造圖片鏈接
sendimagefile=open(r'D:\pythontest\testimage.png','rb').read()
image = MIMEImage(sendimagefile)
image.add_header('Content-ID','<image1>')
image["Content-Disposition"] = 'attachment; filename="testimage.png"'
msg.attach(image)

#構造html
#發送正文中的圖片:由於包含未被許可的信息,網易郵箱定義爲垃圾郵件,報554 DT:SPM :<p><img src="cid:image1"></p>
html = """
<html>  
  <head></head>  
  <body>  
    <p>Hi!<br>  
       How are you?<br>  
       Here is the <a href="http://www.baidu.com">link</a> you wanted.<br> 
    </p> 
  </body>  
</html>  
"""    
text_html = MIMEText(html,'html', 'utf-8')
text_html["Content-Disposition"] = 'attachment; filename="texthtml.html"'   
msg.attach(text_html)    


#構造附件
sendfile=open(r'D:\pythontest\1111.txt','rb').read()
text_att = MIMEText(sendfile, 'base64', 'utf-8') 
text_att["Content-Type"] = 'application/octet-stream'  
#以下附件可以重命名成aaa.txt  
#text_att["Content-Disposition"] = 'attachment; filename="aaa.txt"'
#另一種實現方式
text_att.add_header('Content-Disposition', 'attachment', filename='aaa.txt')
#以下中文測試不ok
#text_att["Content-Disposition"] = u'attachment; filename="中文附件.txt"'.decode('utf-8')
msg.attach(text_att)    
       
#發送郵件
smtp = smtplib.SMTP()    
smtp.connect('smtp.163.com')
#我們用set_debuglevel(1)就可以打印出和SMTP服務器交互的所有信息。
#smtp.set_debuglevel(1)  
smtp.login(username, password)    
smtp.sendmail(sender, receiver, msg.as_string())    
smtp.quit()

複製代碼

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章