import imaplib import email from email.policy import default from html2text import html2text IMAP_SERVER = 'imap.qq.com' # 例如: 'imap.gmail.com' IMAP_PORT = 993 # 默认IMAP端口为993 EMAIL_ADDRESS = '[email protected]' # 你的邮箱地址 EMAIL_PASSWORD = 'xxxxxxxxxxxx' # 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) # 打印邮件主题和内容 print('Subject:', email_message['Subject'].encode('utf-8')) print('From:', email_message['From'].encode('utf-8')) print('To:', email_message['To']) print('Date:', email_message['Date']) 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...')
标签:QQ,以纯,get,python,IMAP,content,mail,message,email From: https://www.cnblogs.com/meetrice/p/18508753