import imaplib
import email
import os
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('youremail@gmail.com', 'yourpassword')
mail.select('inbox')
result, data = mail.search(None, "UNSEEN")
for num in data[0].split():
typ, data = mail.fetch(num, '(RFC822)')
msg = email.message_from_bytes(data[0][1])
# 读取邮件正文
if msg.is_multipart():
body = ""
for part in msg.walk():
ctype = part.get_content_type()
cdispo = str(part.get('Content-Disposition'))
if ctype == 'text/plain' and 'attachment' not in cdispo:
body = part.get_payload(decode=True).decode('utf-8')
else:
body = msg.get_payload(decode=True).decode('utf-8')
# 遍历所有附件
for part in msg.walk():
ctype = part.get_content_type()
cdispo = str(part.get('Content-Disposition'))
# 判断是否是附件
if ctype == 'application/octet-stream' and 'attachment' in cdispo:
filename = part.get_filename()
# 保存附件到指定目录
if filename:
filepath = os.path.join('/path/to/folder', filename)
with open(filepath, 'wb') as f:
f.write(part.get_payload(decode=True))
其中,'/path/to/folder'是你要把附件保存到的目标目录。
for num in data[0].split():
mail.store(num, '+FLAGS', '\\Seen')
下一篇:遍历迭代器会返回相同的值