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從數(shù)據(jù)庫讀取大量數(shù)據(jù)批量寫入文件的方法
今天小編就為大家分享一篇Python從數(shù)據(jù)庫讀取大量數(shù)據(jù)批量寫入文件的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12
python正則表達式re之compile函數(shù)解析
這篇文章主要介紹了python正則表達式re之compile函數(shù)解析,介紹了其定義,匹配模式等相關內(nèi)容,具有一定參考價值,需要的朋友可以了解下。2017-10-10
Python騷操作完美實現(xiàn)短視頻偽原創(chuàng)
剪輯的視頻上傳到某平臺碰到降權怎么辦?視頻平臺都有一套自己的鑒別算法,專門用于處理視頻的二次剪輯,本篇我們來用python做一些特殊處理2022-02-02
Python使用DrissionPage實現(xiàn)網(wǎng)頁自動化采集
DrissionPage 是一個基于 python 的網(wǎng)頁自動化工具,它既能控制瀏覽器,也能收發(fā)數(shù)據(jù)包,還能把兩者合而為一,可兼顧瀏覽器自動化的便利性和 requests 的高效率,本文給大家介紹了Python使用DrissionPage實現(xiàn)網(wǎng)頁自動化采集,需要的朋友可以參考下2025-03-03
Python調(diào)用Google?Bard的圖文詳解
Google?Bard?是一種開源數(shù)據(jù)可視化和探索工具,可為?開發(fā)人員?提供支持,本文主要為大家介紹了Python調(diào)用Google?Bard的方法,需要的可以參考下2023-08-08

