import imaplib
import email
from email.header import decode_header
import webbrowser
import os
# 邮箱登录信息
username = "用户名"
password = "密码"
# 腾讯企业邮箱的IMAP服务器地址和端口
imap_server = "imap.exmail.qq.com"
imap_port = 993
# 连接到IMAP服务器
mail = imaplib.IMAP4_SSL(imap_server, imap_port)
mail.login(username, password)
# 选择收件箱
mail.select("inbox")
# 搜索所有邮件
status, messages = mail.search(None, "ALL")
mail_ids = messages[0].split()
# 定位最新的一封邮件
latest_email_id = mail_ids[-1]
# 获取该邮件的内容
status, msg_data = mail.fetch(latest_email_id, "(RFC822)")
# print(status)
# print(msg_data)
for response_part in msg_data:
if isinstance(response_part, tuple):
# 解析邮件
msg = email.message_from_bytes(response_part[1])
# 邮件发件人
from_ = msg.get("From")
print(f"发件人: {from_}")
# 邮件主题
subject, encoding = decode_header(msg.get("Subject"))[0]
if isinstance(subject, bytes):
# 如果主题是字节,则进行解码
subject = subject.decode(encoding if encoding else "utf-8")
print(f"主题: {subject}")
# 如果邮件是多部分的
if msg.is_multipart():
for part in msg.walk():
content_type = part.get_content_type()
content_disposition = str(part.get("Content-Disposition"))
if "attachment" not in content_disposition:
try:
# 获取邮件正文,并检测编码
body = part.get_payload(decode=True)
charset = part.get_content_charset()
if charset:
body = body.decode(charset, errors="ignore")
else:
body = body.decode("utf-8", errors="ignore")
print(f"正文: {body}")
except Exception as e:
print(f"解码错误: {e}")
else:
# 非多部分邮件,直接读取正文
try:
body = msg.get_payload(decode=True)
charset = msg.get_content_charset()
if charset:
body = body.decode(charset, errors="ignore")
else:
body = body.decode("utf-8", errors="ignore")
print(f"正文: {body}")
except Exception as e:
print(f"解码错误: {e}")
# 退出IMAP服务器
mail.logout()
python操作腾讯企业邮箱读取邮件内容
于 2024-09-13 16:07:28 首次发布