3

使用 jython

我有一种情况,电子邮件带有不同的附件。某些文件类型我处理其他我忽略并且不写入文件的文件。我陷入了一个相当糟糕的境地,因为有时人们将电子邮件作为附件发送,而附加的电子邮件具有合法附件。

我想要做的是跳过附加的电子邮件及其所有附件。

使用 python/jythons 标准电子邮件库我该怎么做?


让它更清楚

我需要解析一封电子邮件(名为 ROOT 电子邮件),我想使用 jython 从这封电子邮件中获取附件。接下来支持某些附件,即.pdf .doc等像。

我需要的是:摆脱附加到根电子邮件和儿童电子邮件附件的任何儿童电子邮件。发生的事情是我浏览了整个电子邮件,它只是解析每个附件,包括根附件和儿童附件,就好像它们是根附件一样。

我不能拥有这个。我只对合法的 ROOT 附件感兴趣,即 .pdf .doc。xls .rtf .tif .tiff

现在应该这样做,我必须跑去赶公共汽车!谢谢!

4

4 回答 4

1

现有建议的问题是 walk 方法。这递归地,深度优先,遍历整个树,包括孩子。

查看 walk 方法的来源,并对其进行调整以跳过递归部分。粗略阅读表明:

if msg.is_multipart():
    for part in msg.get_payload():
          """ Process message, but do not recurse """
          filename = part.get_filename()

阅读 pydocs,get_payload 应该返回一个顶级消息列表,而不是递归。

于 2008-11-26T15:38:34.353 回答
0

那个名为“ Here's an example of how to unpack a MIME message like the above, into a directory of files ”的例子怎么样?它看起来离你想要的很近。

import email
...
msg = email.message_from_file(fp)
...
for part in msg.walk():
    # multipart/* are just containers
    if part.get_content_maintype() == 'multipart':
        continue
    # Applications should really sanitize the given filename so that an
    # email message can't be used to overwrite important files
    filename = part.get_filename()
    if not filename:
        ext = mimetypes.guess_extension(part.get_content_type())
    ...
于 2008-11-26T08:58:31.557 回答
0

您是否尝试过 get_payload( [i[, decode]]) 方法?与 walk 不同,它没有记录递归打开附件。

于 2008-11-26T10:52:21.827 回答
0

我将您的问题理解为“我必须检查电子邮件的所有附件,但如果附件也是电子邮件,我想忽略它。” 无论哪种方式,这个答案都应该引导你走上正确的道路。

我想你想要的是mimetypes.guess_type(). 使用此方法也比仅检查扩展列表要好得多。

def check(self, msg):
    import mimetypes

    for part in msg.walk():
        if part.get_filename() is not None:
            filenames = [n for n in part.getaltnames() if n]
            for filename in filenames:
                type, enc = mimetypes.guess_type(filename)
                if type.startswith('message'):
                    print "This is an email and I want to ignore it."
                else:
                    print "I want to keep looking at this file."

请注意,如果这仍然查看附加的电子邮件,请将其更改为:

def check(self, msg):
    import mimetypes

    for part in msg.walk():
        filename = part.get_filename()
        if filename is not None:
            type, enc = mimetypes.guess_type(filename)
            if type.startswith('message'):
                print "This is an email and I want to ignore it."
            else:
                part_filenames = [n for n in part.getaltnames() if n]
                for part_filename in part_filenames:
                    print "I want to keep looking at this file."

MIME 类型文档

于 2008-11-26T10:59:27.193 回答