import imaplib
import email
from email.header import decode_header
# 配置信息
IMAP_SERVER = "mailx.serv00.com " # mailx.serv00.com x表示你服务器的数字
EMAIL = "[email protected]" # 你的邮箱地址
PASSWORD = "your-password" # 你的邮箱密码
try:
# 连接到 IMAP 服务器
print(f"正在连接到 {IMAP_SERVER}...")
mail = imaplib.IMAP4_SSL(IMAP_SERVER)
# 登录
print("正在登录...")
mail.login(EMAIL, PASSWORD)
print("登录成功!")
# 选择收件箱
mail.select("inbox")
print("已选择收件箱。")
# 搜索邮件(例如:所有邮件)
status, messages = mail.search(None, "ALL")
if status != "OK":
print("未找到邮件。")
exit()
# 获取邮件 ID 列表
email_ids = messages[0].split()
print(f"找到 {len(email_ids)} 封邮件。")
# 遍历每封邮件
for i, email_id in enumerate(email_ids[-5:], start=1): # 只读取最后 5 封邮件
print(f"\n正在读取第 {i} 封邮件...")
# 获取邮件内容
status, msg_data = mail.fetch(email_id, "(RFC822)")
if status != "OK":
print("无法读取邮件内容。")
continue
# 解析邮件内容
for response_part in msg_data:
if isinstance(response_part, tuple):
msg = email.message_from_bytes(response_part[1]) # 解析邮件
# 提取邮件主题
subject, encoding = decode_header(msg["Subject"])[0]
if isinstance(subject, bytes):
subject = subject.decode(encoding or "utf-8")
print(f"主题: {subject}")
# 提取发件人
from_ = msg.get("From")
print(f"发件人: {from_}")
# 提取邮件正文
if msg.is_multipart():
for part in msg.walk():
content_type = part.get_content_type()
content_disposition = str(part.get("Content-Disposition"))
# 提取纯文本内容
if content_type == "text/plain" and "attachment" not in content_disposition:
body = part.get_payload(decode=True).decode()
print(f"正文:\n{body}")
else:
body = msg.get_payload(decode=True).decode()
print(f"正文:\n{body}")
except imaplib.IMAP4.error as e:
print(f"IMAP 错误: {e}")
except Exception as e:
print(f"其他错误: {e}")
finally:
# 关闭连接
if 'mail' in locals():
mail.logout()
print("已断开连接。")
代码解析#
(1) 连接和登录
使用 imaplib.IMAP4_SSL 连接到 IMAP 服务器。
调用 login 方法进行身份验证。
(2) 选择邮箱文件夹
使用 select ("inbox") 选择收件箱。您也可以选择其他文件夹,例如 "Sent" 或 "Drafts"。
(3) 搜索邮件
使用 search (None, "ALL") 查找所有邮件。
返回的 messages 是一个包含邮件 ID 的字节字符串列表。
(4) 获取邮件内容
使用 fetch (email_id, "(RFC822)") 获取指定邮件的完整内容。
RFC822 表示返回完整的邮件数据。
(5) 解析邮件内容
使用 email.message_from_bytes 将邮件数据解析为 MIME 对象。
使用 decode_header 解码邮件主题和发件人信息。
如果邮件是多部分(multipart),遍历每个部分以提取正文或附件。
处理附件#
如果邮件包含附件,可以通过检查 Content-Disposition 来提取附件。以下是处理附件的代码片段:
代码解析#
1. 连接和登录#
- 使用
imaplib.IMAP4_SSL
连接到 IMAP 服务器。 - 调用
login
方法进行身份验证。
2. 选择邮箱文件夹#
- 使用
select("inbox")
选择收件箱。您也可以选择其他文件夹,例如 "Sent" 或 "Drafts"。
3. 搜索邮件#
- 使用
search(None, "ALL")
查找所有邮件。 - 返回的
messages
是一个包含邮件 ID 的字节字符串列表。
4. 获取邮件内容#
- 使用
fetch(email_id, "(RFC822)")
获取指定邮件的完整内容。 RFC822
表示返回完整的邮件数据。
5. 解析邮件内容#
- 使用
email.message_from_bytes
将邮件数据解析为 MIME 对象。 - 使用
decode_header
解码邮件主题和发件人信息。 - 如果邮件是多部分(multipart),遍历每个部分以提取正文或附件。
6. 处理附件#
如果邮件包含附件,可以通过检查 Content-Disposition
来提取附件。以下是处理附件的代码片段:
if "attachment" in content_disposition:
filename = part.get_filename()
if filename:
filepath = f"./attachments/{filename}"
with open(filepath, "wb") as f:
f.write(part.get_payload(decode=True))
print(f"附件已保存: {filepath}")