Python實現郵件自動下載的示例詳解
開始碼代碼之前,我們先來瞭解一下三種郵件服務協議:
1、SMTP協議
SMTP(Simple Mail Transfer Protocol),即簡單郵件傳輸協議。相當於中轉站,將郵件發送到客戶端。
2、POP3協議
POP3(Post Office Protocol 3),即郵局協議的第3個版本,是電子郵件的第一個離線協議標準。該協議把郵件下載到本地計算機,不與服務器同步,缺點是更易丟失郵件或多次下載相同的郵件。
3、IMAP協議
IMAP(Internet Mail Access Protocol),即交互式郵件存取協議。該協議連接遠程郵箱直接操作,與服務器內容同步。
然後介紹一下email包
這個包的中心組件是代表電子郵件消息的“對象模型”。 應用程序主要通過在 message 子模塊中定義的對象模型接口與這個包進行交互。 應用程序可以使用此 API 來詢問有關現有電子郵件的問題、構造新的電子郵件,或者添加或移除自身也使用相同對象模型接口的電子郵件子組件。 也就是說,遵循電子郵件消息及其 MIME 子組件的性質,電子郵件對象模型是所有提供 EmailMessage API 的對象所構成的樹狀結構。
接下來我們通過具體的代碼實現一個登錄郵箱客戶端,下載郵件,解析郵件附件內容的功能。
首先我們需要定義一個郵件解析的類,該類需要三個變量:
1、郵箱所屬的imap服務地址;
2、郵箱賬號;
3、郵箱密碼【註:不同郵箱需要不同的安全策略,例如qq郵箱需要短信驗證,獲取登錄授權碼,而不是明文密碼去登錄遠程客戶端】
class Email_parse: def __init__(self,remote_server_url,email_url,password): # imap服務地址 self.remote_server_url = remote_server_url # 郵箱賬號 self.email_url = email_url # 郵箱密碼 self.password = password
然後定義類中入口函數,登錄遠程,默認獲取第一頁所有的郵件。我們獲取郵件的主題,並打印出來【不同郵件主題的編碼可能不同,二進制需要轉碼才能正確顯示】
def main_parse_Email(self): """入口函數,登錄imap服務""" server = imaplib.IMAP4_SSL(self.remote_server_url, 993) server.login(self.email_url, self.password) server.select('INBOX') status,data = server.search(None,"ALL") if status != 'OK': raise Exception('read email error') emailids = data[0].split() mail_counts = len(emailids) print("count:",mail_counts) # 郵件的遍歷是按時間從後往前,這裡我們選擇最新的一封郵件 for i in range(mail_counts - 1, mail_counts - 2, -1): status, edata = server.fetch(emailids[i], '(RFC822)') msg = email.message_from_bytes(edata[0][1]) #獲取郵件主題title subject = email.header.decode_header(msg.get('subject')) if type(subject[-1][0]) == bytes: title = subject[-1][0].decode(str(subject[-1][1])) elif type(subject[-1][0]) == str: title = subject[-1][0] print("title:", title)
其中,msg變量保存的就是郵件的主體,接下來因為會重復用到msg和tilte,我們將構造一個類函數返回msg和title。
def get_email_title(msg): subject = email.header.decode_header(msg.get('subject')) if type(subject[-1][0]) == bytes: title = subject[-1][0].decode(str(subject[-1][1])) elif type(subject[-1][0]) == str: title = subject[-1][0] print("title:", title) return title
解析郵件,我們分為兩部分,郵件正文【HTML】和附件【xlsx等】,判斷有附件,我們就保存到固定的路徑下。表格的解析不再贅述瞭,pandas之類的包足以搞定。
def get_att(msg): """獲取附件並下載""" filename = Email_parse.get_email_name(msg) for part in msg.walk(): file_name = part.get_param("name") if file_name: data = part.get_payload(decode=True) if data != None: att_file = open('./src/' + filename, 'wb') att_file.write(data) att_file.close() else: pass
郵件正文內容,我們直接解析html,將文本內容直接保存到.txt文件中,方便讀取。
def get_text_from_HTML(msg): """獲取郵件中的html""" filename = Email_parse.get_email_name(msg) current_title = Email_parse.get_email_title(msg) print("filename:",filename,type(filename)) for part in msg.walk(): if not part.is_multipart(): result = part.get_payload(decode=True) result = result.decode('gbk') f = open(f'./src/{current_title}.txt','w') f.write(result) f.close() return result
完整代碼如下:
import email import imaplib from email.header import decode_header import pandas as pd import datetime class Email_parse: def __init__(self,remote_server_url,email_url,password): self.remote_server_url = remote_server_url self.email_url = email_url self.password = password def get_att(msg): filename = Email_parse.get_email_name(msg) for part in msg.walk(): file_name = part.get_param("name") if file_name: data = part.get_payload(decode=True) if data != None: att_file = open('./src/' + filename, 'wb') att_file.write(data) att_file.close() else: pass def get_email_title(msg): subject = email.header.decode_header(msg.get('subject')) if type(subject[-1][0]) == bytes: title = subject[-1][0].decode(str(subject[-1][1])) elif type(subject[-1][0]) == str: title = subject[-1][0] print("title:", title) return title def get_email_name(msg): for part in msg.walk(): file_name = part.get_param("name") if file_name: h = email.header.Header(file_name) dh = email.header.decode_header(h) filename = dh[0][0] if dh[0][1]: value, charset = decode_header(str(filename, dh[0][1]))[0] if charset: filename = value.decode(charset) print("附件名稱:", filename) return filename def main_parse_Email(self): server = imaplib.IMAP4_SSL(self.remote_server_url, 993) server.login(self.email_url, self.password) server.select('INBOX') status,data = server.search(None,"ALL") if status != 'OK': raise Exception('read email error') emailids = data[0].split() mail_counts = len(emailids) print("count:",mail_counts) for i in range(mail_counts - 1, mail_counts - 2, -1): status, edata = server.fetch(emailids[i], '(RFC822)') msg = email.message_from_bytes(edata[0][1]) subject = email.header.decode_header(msg.get('subject')) if type(subject[-1][0]) == bytes: title = subject[-1][0].decode(str(subject[-1][1])) elif type(subject[-1][0]) == str: title = subject[-1][0] print("title:", title) Email_parse.get_att(msg) Email_parse.get_text_from_HTML(msg) def get_text_from_HTML(msg): filename = Email_parse.get_email_name(msg) current_title = Email_parse.get_email_title(msg) print("filename:",filename,type(filename)) for part in msg.walk(): if not part.is_multipart(): result = part.get_payload(decode=True) result = result.decode('gbk') f = open(f'./src/{current_title}.txt','w') f.write(result) f.close() return result if __name__ == "__main__": remote_server_url = 'imap.qq.com' email_url = "*********@qq.com" password = "**********" demo = Email_parse(remote_server_url,email_url,password) demo.main_parse_Email()
運行結果:
以上就是Python實現郵件自動下載的示例詳解的詳細內容,更多關於Python郵件自動下載的資料請關註WalkonNet其它相關文章!
推薦閱讀:
- python使用imap-tools模塊下載郵件中的附件的示例
- Python實現自動化郵件發送過程詳解
- Python自動化辦公之郵件發送全過程詳解
- .NET使用MailKit進行郵件處理的方法步驟
- 詳解Python如何實現發送帶附件的電子郵件