63 lines
1.9 KiB
Python
63 lines
1.9 KiB
Python
import imaplib
|
|
import email
|
|
import json
|
|
from email.header import decode_header
|
|
|
|
# 从JSON文件中加载配置信息
|
|
with open('email_config.json', 'r') as config_file:
|
|
config = json.load(config_file)
|
|
|
|
user = config['sender']
|
|
password = config['password']
|
|
imap_url = config['imap_url']
|
|
|
|
# 连接到IMAP服务器
|
|
mail = imaplib.IMAP4_SSL(imap_url)
|
|
mail.login(user, password)
|
|
mail.select('inbox')
|
|
|
|
# 搜索所有邮件
|
|
result, data = mail.search(None, 'ALL')
|
|
mail_ids = data[0]
|
|
|
|
id_list = mail_ids.split()
|
|
id_list.reverse()
|
|
emails = []
|
|
|
|
# 遍历邮件ID
|
|
for i in id_list:
|
|
result, data = mail.fetch(i, '(RFC822)')
|
|
raw_email = data[0][1]
|
|
raw_email_string = raw_email.decode('utf-8',errors="ignore")
|
|
email_message = email.message_from_string(raw_email_string)
|
|
|
|
# 解析邮件内容
|
|
mail_from = email_message['From']
|
|
mail_subject = decode_header(email_message['Subject'])[0][0]
|
|
if isinstance(mail_subject, bytes):
|
|
mail_subject = mail_subject.decode('utf-8')
|
|
mail_body = ''
|
|
if email_message.is_multipart():
|
|
for part in email_message.walk():
|
|
ctype = part.get_content_type()
|
|
cdispo = str(part.get('Content-Disposition'))
|
|
if ctype == 'text/plain' and 'attachment' not in cdispo:
|
|
mail_body = part.get_payload(decode=True).decode('utf-8')
|
|
break
|
|
else:
|
|
mail_body = email_message.get_payload(decode=True).decode('utf-8')
|
|
|
|
emails.append({'From': mail_from, 'Subject': mail_subject, 'Body': mail_body})
|
|
|
|
# 保存邮件列表到JSON文件
|
|
with open('emails.json', 'w') as outfile:
|
|
json.dump(emails, outfile, indent=4, ensure_ascii=False)
|
|
|
|
# 打印最后一封邮件的信息
|
|
if emails:
|
|
print("From: ", emails[0]['From'])
|
|
print("Subject: ", emails[0]['Subject'])
|
|
print("Body: ", emails[0]['Body'])
|
|
|
|
mail.logout()
|