python使用imap-tools模塊下載郵件附件的示例
最近在做一些email相關的辦公自動化項目,發(fā)現(xiàn)一個第三方模塊imap-tools不錯, 網(wǎng)上沒有啥相關介紹,所以記錄下來.
環(huán)境: python3.8; imap-tools 0.39.0
需要pip 安裝一下imap-tools模塊
imap-tools模塊是python的第三方擴展, 它使用標準庫imaplib,并將常見的郵件處理事件封裝,郵件處理起來代碼短. 下面是個下載郵件附件的示例
from imap_tools import MailBox
with MailBox("imap服務器名").login("賬號", "密碼") as mailbox:
for msg in mailbox.fetch(limit=2,reverse=True): # 我這里為了避免讀取全部的郵件,加上了limit=2的匹配參數(shù),讀取兩封郵件,按照最新接收的次序排序,進行測試;
for att in msg.attachments: # msg為上一行取得的全部郵件
if att.filename: # 如果附件的文件名不為空
att_data = att.payload # 獲得附件的內(nèi)容
f = open(att.filename,'wb') # 用二進制打開,一般郵件附件都是二進制的.
f.write(att_data)
f.close()
就是這么短,用起來比imaplib爽多了.
補充:使用Python的imap和email模塊讀取郵件
SMTP發(fā)送郵件的博文很多,但完整讀取郵件的較少,本文主要是Python3讀取郵件的編碼,同時使用BeautifulSoup解析郵件內(nèi)容。
Python版本信息,如下:
Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)] on win32
代碼
import email
import imaplib
from bs4 import BeautifulSoup
def main():
try:
# 填寫需要讀取郵件服務器的imap的host和port,不知道請聯(lián)系管理員
conn = imaplib.IMAP4_SSL(host='imap.xxx.com', port='993')
# 讀取郵件的用戶名和密碼
conn.login('xxx@qq.com', 'your password')
# 默認選擇收件箱 INBOX
conn.select()
# Recent\Seen參數(shù)不起作用,暫先讀取所有郵件
status, data = conn.search(None, 'ALL')
if status != 'OK':
raise Exception('讀取郵件發(fā)生錯誤')
emailids = data[0].split()
# 倒序讀取郵件
mail_counts = len(emailids)
for i in range(mail_counts-1, 0, -1):
# 獲取郵件信息
status, edata = conn.fetch(emailids[i], '(RFC822)')
# Message對象
msg = email.message_from_bytes(edata[0][1])
# 標題
subject = email.header.decode_header(msg.get('subject'))
# subject包含文檔編碼
default_code = subject[0][1]
# print('Content_Type', msg.get_content_type())
ctype = msg.get_content_type()
# 是否multipart類型,分別處理
if msg.is_multipart():
pl = msg.get_payload()
for m in pl:
ctype = m.get_content_type()
if 'html' in ctype:
# 注意decode參數(shù),如果是True將解碼base64/quoted-printable等格式編碼內(nèi)容,否則不解碼
html = str(m.get_payload(decode=True), m.get('content-type').split('=')[1])
# BeautifulSoup解析網(wǎng)頁
soup = BeautifulSoup(html, "lxml")
divs = soup.select('body')
for d in divs:
# 提取所有文本內(nèi)容
text = d.get_text(strip=True)
print(text)
else:
html = str(msg.get_payload(decode=True), default_code)
# BeautifulSoup解析網(wǎng)頁
soup = BeautifulSoup(html, "lxml")
# 提取body標簽里面的所有文本內(nèi)容
divs = soup.select('body')
for d in divs:
text = d.get_text(strip=True)
print(text)
except Exception as ex:
print(ex)
finally:
# close
conn.close()
conn.logout()
if __name__ == "__main__":
main()
到此這篇關于python使用imap-tools模塊下載郵件中的附件的文章就介紹到這了,更多相關python下載郵件附件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python+Selenium實現(xiàn)網(wǎng)站滑塊拖動操作
這篇文章主要為大家詳細介紹了如何利用Python+Selenium模擬實現(xiàn)登錄某網(wǎng)站的滑塊拖動操作,文中的示例代碼講解詳細,需要的可以參考一下2022-09-09
Python利用卡方Chi特征檢驗實現(xiàn)提取關鍵文本特征
卡方檢驗最基本的思想就是通過觀察實際值與理論值的偏差來確定理論的正確與否。本文將利用卡方Chi特征檢驗實現(xiàn)提取關鍵文本特征功能,感興趣的可以了解一下2022-12-12
Python中yield關鍵字及與return的區(qū)別詳解
這篇文章主要介紹了Python中yield關鍵字及與return的區(qū)別詳解,帶有 yield 的函數(shù)在 Python 中被稱之為 generator生成器,比如列表所有數(shù)據(jù)都在內(nèi)存中,如果有海量數(shù)據(jù)的話將會非常耗內(nèi)存,想要得到龐大的數(shù)據(jù),又想讓它占用空間少,那就用生成器,需要的朋友可以參考下2023-08-08

