Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

用 Python poplib 走 POP3 協議收信

POP(Post Office Protocol)是郵局協議,採用 C/S 工作模式。收信的流程是:先用 DNS 解析 POP 伺服器的 IP 並建立連線,接著以 USER 命令送出帳號、PASS 命令送出密碼,完成認證後就能對信箱做進一步操作。Python 的 poplib 套件包裝了 stat、list、retr 等方法,可以查詢郵件數量與大小、列出郵件資訊、下載信件內容。

要連線並讀取郵件,先建立 POP3 物件並傳入主機與埠號,用 user() 與 pass_() 送出憑證,stat() 取得郵件統計,list() 列出每封信的資訊。

#!/usr/bin/env python
import sys, poplib, getpass, email

(host, user, file) = sys.argv[1:]
passwd = getpass.getpass()
p = poplib.POP3(host)
fd = open(file, "at")
try:
    p.user(user)
    p.pass_(passwd)
except poplib.error_proto, e:
    print "failed to login in"
    sys.exit(-1)

mail = p.stat()
print "There're %d messages and the total size is %d bytes" % (mail[0], mail[1])
for item in p.list()[1]:
    number, bytes = item.split(' ')
    lines = p.retr(number)[1]
    msg = email.message_from_string("\n".join(lines))
    fd.write(msg.as_string(unixfrom=1))
    fd.write('\n')
p.quit()
fd.close()

在 Ubuntu 下執行這支程式,會於當前目錄產生一個檔案,用 cat 就能檢視信件內容。實務上要留意:POP3 預設傳輸是明文,正式環境建議改用 POP3S(poplib.POP3_SSL)以免密碼外洩。

Copyright © Linux教程網 All Rights Reserved