python - 在 python 2.7 中将电子邮件附件保存到文件

标签 python email python-2.7

您好,我有一个类似的问题:

Getting mail attachment to python file object

我想将电子邮件中的所有文件附件保存到硬盘上的文件中。但如果我是正确的,并非多部分电子邮件的所有部分都是“真实”文件(例如电子邮件 html 部分中的一些图像)。我想 100% 确定我保存的文件是附件。

现在我有这个:

mail = "";
for line in sys.stdin:
    mail += line;

msg = email.message_from_string(mail);

for part in msg.walk():
    check if is file and save

最佳答案

基于 http://www.ianlewis.org/en/parsing-email-attachments-python

我设法创建此代码:

import sys;
import email

class Attachement(object):
    def __init__(self):
        self.data = None;
        self.content_type = None;
        self.size = None;
        self.name = None;



def parse_attachment(message_part):
    content_disposition = message_part.get("Content-Disposition", None);
    if content_disposition:
        dispositions = content_disposition.strip().split(";");
        if bool(content_disposition and dispositions[0].lower() == "attachment"):

            attachment = Attachement();
            attachment.data = message_part.get_payload(decode=True);
            attachment.content_type = message_part.get_content_type();
            attachment.size = len(attachment.data);
            attachment.name = message_part.get_filename();

            return attachment;

    return None;


if __name__=='__main__':

    mail = "";
    for line in sys.stdin:
        mail += line;


    msg = email.message_from_string(mail);

    attachements = list();

    if(msg.is_multipart()):
        for part in msg.walk():
            attachement = parse_attachment(part);
            if(attachement):
                attachements.append(attachement);




    for att in attachements:
        # write file in binary mode
        file = open(att.name, 'wb');
        file.write(att.data);
        file.close();



    print 'OK';

关于python - 在 python 2.7 中将电子邮件附件保存到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23080859/

相关文章:

python - 使用 HTML 模板的 Django 表单

python - 我可以嵌套 virtualenvs 吗?

git - 使用 git send-email 回复邮件列表中的同一线程

python - 使用带有口音和不同字符的 Beautiful Soup

python - 在 Django 中使用带有外键的模型的正确方法

python - Django模型.参数

c++ - Smtp 客户端 - 从和不发送

java - 如何使用 Java Mail API 验证电子邮件和密码?

python - 在 python 中的文件内搜索

google-app-engine - 为什么在分页第 2 页的第二次点击时出现 "InvalidRequest"?