python从QQ邮箱中读取最新邮件,并以纯文本的方式在控制台显示

import imaplib
import email
from email.header import decode_header
from email.utils import parsedate_to_datetime
from html2text import html2text
from datetime import datetime


IMAP_SERVER = 'imap.qq.com'  # 例如: 'imap.gmail.com'  
IMAP_PORT = 993  # 默认IMAP端口为993  
EMAIL_ADDRESS = 'yourname@qq.com'  # 你的邮箱地址  
EMAIL_PASSWORD = 'xxxxxxxxxxxxxx'  # IMAP授权密码

# 创建 IMAP 连接
mail = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT)

# 登录邮箱
mail.login(EMAIL_ADDRESS, EMAIL_PASSWORD)

# 选择邮箱文件夹
mail.select('INBOX')

# 搜索符合条件的邮件
result, data = mail.search(None, 'ALL')

# 获取邮件编号列表
email_ids = data[0].split()

# 获取最新一封邮件的内容
latest_email_id = email_ids[-1]
result, data = mail.fetch(latest_email_id, '(RFC822)')

# 解析邮件内容
raw_email = data[0][1]
email_message = email.message_from_bytes(raw_email)

subject, encoding = decode_header(email_message['Subject'])[0]
if isinstance(subject, bytes):
    subject = subject.decode(encoding if encoding else 'utf-8')
print('标题:', subject)
print('寄件人:', email_message['From'].encode('utf-8'))
print('收件人:', email_message['To'])
local_time_str = datetime.fromtimestamp(parsedate_to_datetime(email_message['Date']).timestamp()).strftime('%Y-%m-%d %H:%M:%S')
print('日期:', local_time_str)

payload = email_message.get_payload(decode=True)

text_content = ""
if email_message.is_multipart():
    # 如果邮件是多部分消息,则递归处理每个部分
    for part in email_message.get_payload():
        if part.get_content_type() == "text/html":
            text_content += part.get_payload(decode=True).decode(part.get_content_charset() or 'utf-8')
else:
    text_content = email_message.get_payload(decode=True).decode('utf-8')

print('内容:',html2text(text_content))


# 关闭连接
mail.logout()
input('Press Enter to exit...')

 

posted @ 2024-10-27 19:04  meetrice  阅读(56)  评论(0编辑  收藏  举报