[http://blog.csdn.net/menglei8625/article/details/7721746]
SMTP (Simple Mail Transfer Protocol)
郵件傳送代理 (Mail Transfer Agent,MTA) 程序使用SMTP協議來發送電郵到接收者的郵件服務器。SMTP協議只能用來發送郵件,不能用來接收郵件。大多數的郵件發送服務器 (Outgoing Mail Server) 都是使用SMTP協議。SMTP協議的默認TCP端口號是25。
POP協議和IMAP協議是用於郵件接收的最常見的兩種協議。幾乎所有的郵件客戶端和服務器都支持這兩種協議。
POP3協議為用戶提供了一種簡單、標准的方式來訪問郵箱和獲取電郵。使用POP3協議的電郵客戶端通常的工作過程是:連接服務器、獲取所有信息並保存在用戶主機、從服務器刪除這些消息然后斷開連接。POP3協議的默認TCP端口號是110。
每封郵件都有兩個部分:郵件頭和郵件體,兩者使用一個空行分隔。
郵件頭每個字段 (Field) 包括兩部分:字段名和字段值,兩者使用冒號分隔。有兩個字段需要注意:From和Sender字段。From字段指明的是郵件的作者,Sender字段指明的是郵件的發送者。如果From字段包含多於一個的作者,必須指定Sender字段;如果From字段只有一個作者並且作者和發送者相同,那么不應該再使用Sender字段,否則From字段和Sender字段應該同時使用。
郵件體包含郵件的內容,它的類型由郵件頭的Content-Type字段指明。RFC 2822定義的郵件格式中,郵件體只是單純的ASCII編碼的字符序列。
MIME (Multipurpose Internet Mail Extensions) (RFC 1341)
__getitem__,__setitem__實現obj[key]形式的訪問。
Msg.attach(playload): 向當前Msg添加playload。
Msg.set_playload(playload): 把整個Msg對象的郵件體設成playload。
在3.0版本的email模塊 (Python 2.3-Python 2.5) 中,這個類位於email.MIMEMultipart.MIMEMultipart。
HTML形式的郵件
郵件傳送代理 (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()
- #!/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()
