自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Python接收郵件的幾種方式

開發(fā) 后端
工作中,我們基本上都用過電子郵件的客戶端,比如說 OutLook,F(xiàn)oxmail,從配置項可以知道,SMTP 協(xié)議用于發(fā)送郵件,POP3 和 IMAP 協(xié)議用于接收郵件。

[[405764]]

工作中,我們基本上都用過電子郵件的客戶端,比如說 OutLook,F(xiàn)oxmail,從配置項可以知道,SMTP 協(xié)議用于發(fā)送郵件,POP3 和 IMAP 協(xié)議用于接收郵件。其實很多編程語言都有這類協(xié)議的實現(xiàn),Python 自然也不例外,標準庫 smtplib、poplib、imaplib 是對應協(xié)議的實現(xiàn)。

至于發(fā)送郵件,不推薦初學者使用 smtplib,推薦使用 djangomail,具體方法見前文最簡單的方式發(fā)送郵件,讓程序出錯自動發(fā)郵件。

今天分享如何使用 poplib、imaplib 來接收郵件。

你說這兩個都可以用來收郵件,到底用哪一個呢?先看下他們的區(qū)別。

POP3 與 IMAP 的區(qū)別

POP3 協(xié)議是 Post Office Protocol 3 的簡稱,即郵局協(xié)議的第 3 個版本,是 TCP/IP 協(xié)議族中的一員,默認端口是110。本協(xié)議主要用于支持使用客戶端遠程管理在服務器上的電子郵件。

IMAP 全稱是 Internet Mail Access Protocol,即交互式郵件訪問協(xié)議,是一個應用層協(xié)議,端口是 143。用來從本地郵件客戶端訪問遠程服務器上的郵件。

POP3 工作在傳輸層,而 IMAP 工作中應用層,從這一點來看,IMAP 更為高級,事實上正是如此。雖然這兩個協(xié)議都是從郵件服務器下載郵件到本地,但是不同的是 IMAP 提供雙向通信,也即在客戶端所作的更改會反饋給服務器端,跟服務器端形成同步,例如刪除郵件,創(chuàng)建文件夾等。而 POP3 是單向通信的,即下載郵件到本地就算了,所作的更改都只是在客戶端,不會反映到服務器端。所以使用 IMAP 協(xié)議也會更便捷,體驗更好,更可靠。

因此,如果你希望對郵件的更改同步到服務端,那么使用 IMAP,否則使用 POP3

POP3 發(fā)送郵件

以下面的代碼為例,我們來獲取最新的一封郵件內容:

  1. import poplib 
  2. from email.parser import Parser 
  3. from utils import print_info 
  4. import settings 
  5.  
  6.  
  7. # 連接到POP3服務器: 
  8. server = poplib.POP3(settings.pop3_server) 
  9. # 身份認證: 
  10. server.user(settings.email) 
  11. server.pass_(settings.password
  12.  
  13. # stat()返回郵件數(shù)量和占用空間: 
  14. print('Messages: %s. Size: %s' % server.stat()) 
  15. # list()返回所有郵件的編號: 
  16. resp, mails, octets = server.list() 
  17. # 可以查看返回的列表類似[b'1 82923', b'2 2184', ...] 
  18.  
  19. # 獲取最新一封郵件, 注意索引號從1開始: 
  20. latest_mail_index = len(mails) 
  21. resp, lines, octets = server.retr(latest_mail_index) 
  22.  
  23. # lines存儲了郵件的原始文本的每一行, 
  24. # 可以獲得整個郵件的原始文本: 
  25. msg_content = b'\r\n'.join(lines).decode('utf-8'
  26. # 稍后解析出郵件: 
  27. msg = Parser().parsestr(msg_content) 
  28. print_info(msg) 
  29. # 郵件索引號直接從服務器刪除郵件 
  30. # server.dele(index
  31. # 關閉連接: 
  32. server.quit() 

執(zhí)行結果如下:

poplib 收取郵件分兩步:第一步是獲取郵件列表,第二步是用 email 模塊把原始郵件解析為 Message 對象,然后,用適當?shù)男问桨燕]件內容展示出來。print_info 函數(shù)的邏輯比較復雜,放在了 utils.py 中,完整代碼見文末的鏈接。

基于 poplib 的三方庫

使用完標準庫 poplib,也使用過三方庫 zmail,我只想說,還是三方庫用起來爽。

zmail

Zmail 使得在 Python3 中發(fā)送和接受郵件變得更簡單。你不需要手動添加服務器地址、端口以及適合的協(xié)議,zmail 會幫你完成。此外,使用一個字典來代表郵件內容也更符合直覺。

Zmail 僅支持 Python3,不依賴任何三方庫。安裝方法:

  1. pip install zmail 

特性:

  • 自動尋找服務器地址以及端口
  • 自動使用可靠的鏈接協(xié)議
  • 自動將一個python字典映射成MIME對象(帶有附件的)
  • 自動添加頭文件以及l(fā)ocalhostname來避免服務器拒收你的郵件
  • 輕松自定義你的頭文件
  • 支持使用HTML作為郵件內容
  • 僅需 python>=3.5,你可以將其嵌入你的項目而無需其他的依賴

示例代碼:

  1. import zmail 
  2. server = zmail.server('yourmail@example.com''yourpassword'
  3.  
  4. # Send mail 
  5. server.send_mail('yourfriend@example.com',{'subject':'Hello!','content_text':'By zmail.'}) 
  6. Or to a list of friends. 
  7. server.send_mail(['friend1@example.com','friend2@example.com'],{'subject':'Hello!','content_text':'By zmail.'}) 
  8.  
  9. # Retrieve mail 
  10. latest_mail = server.get_latest() 
  11. zmail.show(latest_mail) 

可以看出,接收最新的郵件只需要兩行代碼:

  1. latest_mail = server.get_latest() 
  2. zmail.show(latest_mail) 

執(zhí)行結果如下:

很簡潔,很好用。

文檔:https://github.com/zhangyunhao116/zmail/blob/master/README-cn.md

imap 接收郵件

很多主流郵箱如 163,qq 郵箱默認關閉了 imap 的服務,可手動前往郵箱賬戶設置頁面開啟,并生成授權碼,授權碼就是代碼中用于登錄的密碼。

獲取最新的郵件并展示:

  1. import imaplib 
  2. import email  #導入兩個庫 
  3. import settings 
  4. from utils import print_info 
  5.  
  6. M = imaplib.IMAP4_SSL(host = settings.imap_server) 
  7. print('已連接服務器'
  8. M.login(settings.email,settings.password
  9. print('已登陸'
  10. print(M.noop()) 
  11. M.select() 
  12.  
  13. typ, data = M.search(None, 'ALL'
  14. for num in data[0].split(): 
  15.     typ, data = M.fetch(num, '(RFC822)'
  16.     # print('Message %s\n%s\n' % (num, data[0][1])) 
  17.     # print(data[0][1].decode('utf-8')) 
  18.     msg = email.message_from_string(data[0][1].decode('utf-8')) 
  19.     print_info(msg) 
  20.     break 
  21. M.close() 
  22. M.logout() 

運行結果如下:

基于 imaplib 的三方庫

你可能會問:為什么要為 Python 創(chuàng)建另一個 IMAP 客戶端庫?Python 標準庫不是已經有 imaplib 了嗎?。

imaplib 的問題在于它非常底層。使用起來相當復雜,你可能需要處理很多細節(jié)問題,由于 IMAP 服務器響應可能非常復雜,這意味著使用 imaplib 的每個人最終都會編寫自己的脆弱解析程序。

此外,imaplib 沒有很好地利用異常。這意味著您需要檢查 imaplib 的每次調用的返回值,以查看請求是否成功。下面推薦兩個常用的三方庫。

imapclient

imapclient 在內部使用的 imaplib,但比 imaplib 好用的多,示例代碼如下:

  1. import ssl 
  2. from imapclient import IMAPClient 
  3. import settings 
  4. # context manager ensures the session is cleaned up 
  5.  
  6.  
  7. ssl_context = ssl.create_default_context() 
  8. # don't check if certificate hostname doesn't match target hostname 
  9. ssl_context.check_hostname = False 
  10. # don't check if the certificate is trusted by a certificate authority 
  11. ssl_context.verify_mode = ssl.CERT_NONE 
  12.  
  13. with IMAPClient(host=settings.imap_server,ssl_context=ssl_context) as client: 
  14.     client.login(settings.account,settings.password
  15.     select_info = client.select_folder('INBOX'
  16.     print('%d messages in INBOX' % select_info[b'EXISTS']) 
  17.     # search criteria are passed in a straightforward way 
  18.     # (nesting is supported) 
  19.     messages = client.search(['FROM''xxxx@163.com']) 
  20.     # `response` is keyed by message id and contains parsed, 
  21.     # converted response items. 
  22.     for message_id, data in client.fetch(messages, ['ENVELOPE']).items(): 
  23.         envelope = data[b'ENVELOPE'
  24.         print('{id}: subject: {subject} date: {date}'.format( 
  25.             id=message_id, 
  26.             subject = envelope.subject.decode(), 
  27.             date = envelope.date 
  28.         )) 

文檔:https://github.com/mjs/imapclient

imap_tools

通過 IMAP 處理電子郵件和郵箱,支持以下功能:

  • 解析的電子郵件消息屬性
  • 用于搜索電子郵件的查詢生成器
  • 使用電子郵件的操作:復制、刪除、標記、移動、看到、追加
  • 使用文件夾的操作:列表、設置、獲取、創(chuàng)建、存在、重命名、刪除、狀態(tài)

沒有依賴項

  1. pip install imap-tools 

示例代碼:

  1. from imap_tools import MailBox, AND 
  2.  
  3. # get list of email subjects from INBOX folder 
  4. with MailBox('imap.mail.com').login('test@mail.com''pwd'as mailbox: 
  5.     subjects = [msg.subject for msg in mailbox.fetch()] 
  6.  
  7. # get list of email subjects from INBOX folder - equivalent verbose version 
  8. mailbox = MailBox('imap.mail.com'
  9. mailbox.login('test@mail.com''pwd', initial_folder='INBOX')  # or mailbox.folder.set instead 3d arg 
  10. subjects = [msg.subject for msg in mailbox.fetch(AND(all=True))] 
  11. mailbox.logout() 

文檔:https://github.com/ikvk/imap_tools

最后的話

完整示例代碼:https://github.com/somenzz/tutorial/tree/master/email

 

使用標準庫有助于我們加深對郵件協(xié)議細節(jié)的理解,而三方庫卻可以不用考慮過多細節(jié),直接上手,標準庫相當于手動擋,三方庫相當于自動擋,具體用哪個,選擇最適合自己的就好。

 

責任編輯:武曉燕 來源: Python七號
相關推薦

2020-07-14 09:58:01

Python開發(fā)工具

2023-11-08 07:51:11

RabbitMQ接收消息

2021-01-19 11:56:19

Python開發(fā)語言

2023-10-25 18:18:10

Python腳本代碼

2023-05-07 07:56:53

Python方式

2022-11-03 15:22:15

數(shù)據結構Python

2016-02-16 10:26:58

PythonXML方式

2021-05-07 16:19:36

異步編程Java線程

2010-05-25 18:19:41

postfix郵件

2010-09-25 14:48:55

SQL連接

2022-05-27 06:57:50

Python循環(huán)方式生成器

2010-11-24 09:56:20

mysql拷貝表

2021-08-02 11:13:28

人工智能機器學習技術

2021-10-07 20:36:45

Redis集群場景

2023-09-07 13:21:00

Linux軟件

2023-02-08 08:43:55

前端繼承原型

2022-08-01 08:30:26

Python命令行

2020-09-28 15:49:25

Python編程語言工具

2024-08-27 13:47:03

2024-05-10 07:44:23

C#進程程序
點贊
收藏

51CTO技術棧公眾號