1. 程式人生 > >Python_使用smtplib和email模組傳送郵件

Python_使用smtplib和email模組傳送郵件

SMTP (Simple Mail Transfer Protocol)
  郵件傳送代理 (Mail Transfer Agent,MTA) 程式使用SMTP協議來發送電郵到接收者的郵件伺服器。SMTP協議只能用來發送郵件,不能用來接收郵件。大多數的郵件傳送伺服器 (Outgoing Mail Server) 都是使用SMTP協議。SMTP協議的預設TCP埠號是25。

  SMTP協議的一個重要特點是它能夠接力傳送郵件。它工作在兩種情況下:一是電子郵件從客戶機傳輸到伺服器;二是從某一個伺服器傳輸到另一個伺服器。

POP3 (Post Office Protocol) & IMAP (Internet Message Access Protocol)

  POP協議和IMAP協議是用於郵件接收的最常見的兩種協議。幾乎所有的郵件客戶端和伺服器都支援這兩種協議。
  POP3協議為使用者提供了一種簡單、標準的方式來訪問郵箱和獲取電郵。使用POP3協議的電郵客戶端通常的工作過程是:連線伺服器、獲取所有資訊並儲存在使用者主機、從伺服器刪除這些訊息然後斷開連線。POP3協議的預設TCP埠號是110。

  IMAP協議也提供了方便的郵件下載服務,讓使用者能進行離線閱讀。使用IMAP協議的電郵客戶端通常把資訊保留在伺服器上直到使用者顯式刪除。這種特性使得多個客戶端可以同時管理一個郵箱。IMAP協議提供了摘要瀏覽功能,可以讓使用者在閱讀完所有的郵件到達時間、主題、發件人、大小等資訊後再決定是否下載。IMAP協議的預設TCP埠號是143。

郵件格式 (RFC 2822)
  每封郵件都有兩個部分:郵件頭和郵件體,兩者使用一個空行分隔。
  郵件頭每個欄位 (Field) 包括兩部分:欄位名和欄位值,兩者使用冒號分隔。有兩個欄位需要注意:From和Sender欄位。From欄位指明的是郵件的作者,Sender欄位指明的是郵件的傳送者。如果From欄位包含多於一個的作者,必須指定Sender欄位;如果From欄位只有一個作者並且作者和傳送者相同,那麼不應該再使用Sender欄位,否則From欄位和Sender欄位應該同時使用。
  郵件體包含郵件的內容,它的型別由郵件頭的Content-Type欄位指明。RFC 2822定義的郵件格式中,郵件體只是單純的ASCII編碼的字元序列。
MIME (Multipurpose Internet Mail Extensions) (RFC 1341)

  MIME擴充套件郵件的格式,用以支援非ASCII編碼的文字、非文字附件以及包含多個部分 (multi-part) 的郵件體等。

Python email模組

1. class email.message.Message
__getitem__,__setitem__實現obj[key]形式的訪問。
Msg.attach(playload): 向當前Msg新增playload。
Msg.set_playload(playload): 把整個Msg物件的郵件體設成playload。

Msg.add_header(_name, _value, **_params): 新增郵件頭欄位。

2. class email.mime.base.MIMEBase(_maintype, _subtype, **_params)

  所有MIME類的基類,是email.message.Message類的子類。

3. class email.mime.multipart.MIMEMultipart()
  在3.0版本的email模組 (Python 2.3-Python 2.5) 中,這個類位於email.MIMEMultipart.MIMEMultipart。

  這個類是MIMEBase的直接子類,用來生成包含多個部分的郵件體的MIME物件。

4. class email.mime.text.MIMEText(_text)

  使用字串_text來生成MIME物件的主體文字。

發郵件程式碼範例:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
 
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
 
# python 2.3.*: email.Utils email.Encoders
from email.utils import COMMASPACE,formatdate
from email import encoders
 
import os
 
#server['name'], server['user'], server['passwd']
def send_mail(server, fro, to, subject, text, files=[]): 
    assert type(server) == dict 
    assert type(to) == list 
    assert type(files) == list 
 
    msg = MIMEMultipart() 
    msg['From'] = fro 
    msg['Subject'] = subject 
    msg['To'] = COMMASPACE.join(to) #COMMASPACE==', ' 
    msg['Date'] = formatdate(localtime=True) 
    msg.attach(MIMEText(text)) 
 
    for file in files: 
        part = MIMEBase('application', 'octet-stream') #'octet-stream': binary data 
        part.set_payload(open(file, 'rb'.read())) 
        encoders.encode_base64(part) 
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file)) 
        msg.attach(part) 
 
    import smtplib 
    smtp = smtplib.SMTP(server['name']) 
    smtp.login(server['user'], server['passwd']) 
    smtp.sendmail(fro, to, msg.as_string()) 
    smtp.close()

檔案形式的郵件:

#!/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('<html><h1>你好</h1></html>','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.<br><img src="cid:image1"><br>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', '<image1>')  
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 = """\ 
<html> 
  <head></head> 
  <body> 
    <p>Hi!<br> 
       How are you?<br> 
       Here is the <a href="http://www.python.org">link</a> you wanted. 
    </p> 
  </body> 
</html> 
"""  
  
# 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()