python - 在 python 中解析多部分电子邮件并保存附件

标签 python email gmail attachment imaplib

我是 python 的新手,我正在尝试通过 python 的 imaplib 和电子邮件解析来自 gmail 的电子邮件。它运行良好,但我在处理电子邮件附件时遇到问题。

我想从电子邮件中解析出所有纯文本,同时忽略任何可能作为次要内容类型插入的 HTML,同时删除并保存所有其他附件。我一直在尝试以下操作:

...imaplib connection and mailbox selection...

typ, msg_data = c.fetch(num, '(RFC822)')
        email_body = msg_data[0][1]
mail = email.message_from_string(email_body)
        for part in mail.walk():
            if part.get_content_type() == 'text/plain':
                body = body + '\n' + part.get_payload()
            else:
                continue

这是我最初尝试只获取电子邮件的明文部分的尝试,但是当有人发送带有文本附件的电子邮件时,文本文件的内容会显示在上面的“正文”变量中。

谁能告诉我如何提取电子邮件的纯文本部分,同时忽略有时出现的辅助 HTML,同时将所有其他类型的文件附件保存为文件?如果这没有多大意义,我深表歉意。如果需要,我会更详细地更新问题。

最佳答案

如果您只需要将文本附件保存在 body 变量之外,那么它应该像这样简单:

mail = email.message_from_string(email_body)
    for part in mail.walk():
        c_type = part.get_content_type()
        c_disp = part.get('Content-Disposition')

        if c_type == 'text/plain' and c_disp == None:
            body = body + '\n' + part.get_payload()
        else:
            continue

然后,如果 Content-Disposition 指示它是附件,您应该能够使用 part.get_filename()part.get_payload() 来处理文件.我不知道这是否会有所不同,但这基本上是我过去用来连接邮件服务器的方式。

关于python - 在 python 中解析多部分电子邮件并保存附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6255202/

相关文章:

python - 对Python中的反斜杠感到困惑

python - 函数没有等待预定的时间 - Python Selenium

Python:项目的子列表取决于项目的某个值,例如 boolean 值

c# - System.Net.Mail AlternateViews 丢失纯文本数据

Java邮件: force "Content-Transfer-Encoding" to be "quoted-printable"

python - 计算 .txt 中单词的长度

python - 使用Python使用Gmail发送电子邮件

ios - 如何获取 UITextView 值以在应用程序邮件中发送?

php - 在 PHP 中从 G-mail 中获取带有特定标签的电子邮件

javascript - 获取邮件的 Gmail API 限制