郵件接收
python3可以使用poplib.POP3進行郵件接收,具體如下:
import poplib
from email.parser import Parser
def get_email(email,password,host="mail.163.com"):
# connect to pop3 server
server = poplib.POP3(host)
# open debug
server.set_debuglevel(1)
# 身份驗證
server.user(email)
server.pass_(password)
# 返回郵件總數目和占用服務器的空間大小(字節數), 通過stat()方法即可
# print("Mail counts: {0}, Storage Size: {0}".format(server.stat()))
# 使用list()返回所有郵件的編號,默認為字節類型的串
resp, mails, octets = server.list()
# print("響應信息: ", resp)
# print("所有郵件簡要信息: ", mails)
# print("list方法返回數據大小(字節): ", octets)
# get the latest, index from 1:
index = len(mails)
if index < 1:
return None
resp, lines, octets = server.retr(index)
# 可以獲得整個郵件的原始文本:
msg_content = b'\r\n'.join(lines).decode('utf-8')
# 解析出郵件:
msg = Parser().parsestr(msg_content)
# print(msg)
# print("解碼后的郵件信息:\r\n"+str(msg))
#close
server.close()
return msg
def delete_email(email,password,host="mail.163.com"):
# connect to pop3 server
server = poplib.POP3(host)
# open debug
# server.set_debuglevel(1)
# 身份驗證
server.user(email)
server.pass_(password)
# 使用list()返回所有郵件的編號,默認為字節類型的串
# list()返回tuple
resp, mails, octets = server.list()
# print("響應信息: ", resp)
# print("所有郵件簡要信息: ", mails)
# print("list方法返回數據大小(字節): ", octets)
# get the latest, index from 1:
index = len(mails)
# 刪除所有郵件
while index > 0:
server.dele(index)
print(index)
index = index -1
# commit command and close
server.quit()
郵件解析
# 解析郵件正文
def get_mail_content(msg):
if msg == None:
return None
for part in msg.walk():
if not part.is_multipart():
data = part.get_payload(decode=True)
# print("emailcontent:\r\n"+data.decode())
return data.decode()
poplib關鍵函數解析
- POP3.dele(which)
標記消息號 which 以進行刪除。在大多數服務器上,刪除直到QUIT才被實際執行(主要例外是Eudora QPOP,它通過在任何斷開連接上進行未決刪除而故意違反RFC)。
- POP3.quit()
注銷:提交更改,解鎖郵箱,刪除連接。
email.message關鍵函數解析
- walk()
walk() 方法是一種通用的生成器,可用於以深度優先遍歷順序遍歷消息對象樹的所有部分和子部分。您通常會在 for 循環中使用 walk() 作為迭代器;每次迭代返回下一個子部分。
- is_multipart()
is_multipart()
如果消息的有效內容是一個子EmailMessage 對象的列表,則返回 True,否則返回 False。當 is_multipart() 返回 False 時,有效負載應為字符串對象(可能是CTE編碼的二進制有效負載)。注意,is_multipart() 返回 True 並不一定意味着“msg.get_content_maintype() == ‘multipart’”將返回 True。例如,當 EmailMessage 類型為 message/rfc822 時,is_multipart 將返回 True。
- get_content_type()
get_content_type()返回消息的內容類型,強制為表格 maintype/subtype 的小寫。如果消息中沒有 Content-Type 頭,則返回 get_default_type() 返回的值。如果 Content-Type 頭無效,則返回 text/plain。
(根據 RFC 2045,消息總是有一個默認類型,get_content_type() 將總是返回一個值。RFC 2045 定義一個消息的默認類型為 text/plain,除非它出現在一個 multipart/digest 容器中,在這種情況下,它將是 message/rfc822 如果 Content-Type 頭有一個無效的類型規范,RFC 2045 強制默認類型為 text/plain。)