python3能夠使用poplib.POP3進行郵件接收,具體以下:html
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()
POP3.dele(which)python
標記消息號 which 以進行刪除。在大多數服務器上,刪除直到QUIT才被實際執行(主要例外是Eudora QPOP,它經過在任何斷開鏈接上進行未決刪除而故意違反RFC)。服務器
POP3.quit()函數
註銷:提交更改,解鎖郵箱,刪除鏈接。ui
walk()編碼
walk() 方法是一種通用的生成器,可用於以深度優先遍歷順序遍歷消息對象樹的全部部分和子部分。您一般會在 for 循環中使用 walk() 做爲迭代器;每次迭代返回下一個子部分。debug
is_multipart()code
is_multipart()
若是消息的有效內容是一個子EmailMessage 對象的列表,則返回 True,不然返回 False。當 is_multipart() 返回 False 時,有效負載應爲字符串對象(多是CTE編碼的二進制有效負載)。注意,is_multipart() 返回 True 並不必定意味着「msg.get_content_maintype() == ‘multipart’」將返回 True。例如,當 EmailMessage 類型爲 message/rfc822 時,is_multipart 將返回 True。orm
get_content_type()server
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。)