要解析邮件并提取邮件内容和附件,可以使用Python的email库。以下是一个示例代码,可以帮助你完成这个任务:

import os
import email
import imaplib
import datetime
from email.header import decode_header

# 邮箱登录信息
username = "your_email@example.com"
password = "your_password"
imap_server = "imap.example.com"

# 连接到IMAP服务器
imap = imaplib.IMAP4_SSL(imap_server)
imap.login(username, password)
imap.select("INBOX")

# 搜索邮件
status, messages = imap.search(None, "ALL")
messages = messages[0].split()

for msg_id in messages:
    # 获取邮件
    status, data = imap.fetch(msg_id, "(RFC822)")
    raw_email = data[0][1]
    email_message = email.message_from_bytes(raw_email)

    # 提取邮件内容
    subject = decode_header(email_message["Subject"])[0][0]
    from_ = decode_header(email_message["From"])[0][0]
    to = decode_header(email_message["To"])[0][0]
    date = decode_header(email_message["Date"])[0][0]

    print("Subject:", subject)
    print("From:", from_)
    print("To:", to)
    print("Date:", date)

    # 提取附件
    for part in email_message.walk():
        if part.get_content_maintype() == "multipart":
            continue
        if part.get("Content-Disposition") is None:
            continue

        filename = part.get_filename()
        if filename:
            filepath = os.path.join("attachments", filename)
            if not os.path.isfile(filepath):
                with open(filepath, "wb") as f:
                    f.write(part.get_payload(decode=True))
            print("Saved attachment:", filename)

# 关闭连接
imap.close()
imap.logout()

在上述代码中,你需要将your_email@example.comyour_password替换为你的邮箱登录信息,将imap.example.com替换为你的IMAP服务器地址。代码会连接到IMAP服务器,搜索所有邮件,并逐个解析邮件内容和附件。邮件内容中的主题、发件人、收件人和日期会被提取并打印出来,附件会被保存在当前目录下的attachments文件夹中。

请注意,此代码仅适用于IMAP协议。如果你使用的是POP3协议,需要使用poplib库来连接和获取邮件。另外,如果你的邮件服务器使用了其他安全协议(如STARTTLS),你需要相应地修改代码来适应

python 解析邮件提取邮件内容及附件

原文地址: https://www.cveoy.top/t/topic/hy6n 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录