AppleScript - 将电子邮件信息提取为 MIME 对象

AppleScript - extract an email message as a MIME object

我写了一个 AppleScript 来对 Mail.app 消息进行一些解析,但是我似乎需要比提供的更强大的处理能力(具体来说 - 将回复的消息与它引用的原始消息分开)通过 AppleScript(比如,使用 Python 的 email 包)。是否可以获取 MIME 字符串形式的电子邮件?

我不确定这是否是您的意思,但这里是您如何从您在 Mail.app 中所做的选择中获取原始消息文本,然后可以使用 MIME 工具进行处理以提取所有部分。

tell application "Mail"
    set msgs to selection
    if length of msgs is not 0 then
        repeat with msg in msgs

            set messageSource to source of msg

            set textFile to "/Users/harley/Desktop/foo.txt"

            set myFile to open for access textFile with write permission
            write messageSource to myFile
            close access myFile

        end repeat
    end if
end tell

然后这里是一个 Python 电子邮件示例脚本,它解压缩邮件并将每个 MIME 部分写到目录中的单独文件中

https://docs.python.org/3.4/library/email-examples.html

#!/usr/bin/env python3

"""Unpack a MIME message into a directory of files."""

import os
import sys
import email
import errno
import mimetypes

from argparse import ArgumentParser


def main():
    parser = ArgumentParser(description="""\
Unpack a MIME message into a directory of files.
""")
    parser.add_argument('-d', '--directory', required=True,
                        help="""Unpack the MIME message into the named
                        directory, which will be created if it doesn't already
                        exist.""")
    parser.add_argument('msgfile')
    args = parser.parse_args()

    with open(args.msgfile) as fp:
        msg = email.message_from_file(fp)

    try:
        os.mkdir(args.directory)
    except FileExistsError:
        pass

    counter = 1
    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())
            if not ext:
                # Use a generic bag-of-bits extension
                ext = '.bin'
            filename = 'part-%03d%s' % (counter, ext)
        counter += 1
        with open(os.path.join(args.directory, filename), 'wb') as fp:
            fp.write(part.get_payload(decode=True))


if __name__ == '__main__':
    main()

那么如果 unpack.py 脚本在 AppleScript 输出上是 运行...

python unpack.py -d OUTPUT ./foo.txt 

您将获得一个 MIME 部分分开的目录。当我 运行 在引用原始消息的消息上使用此消息时,原始消息将显示在单独的部分中。