我写了一个 AppleScript 来对 Mail.app 消息进行一些解析,但似乎我需要比 AppleScript 提供的更强大的处理(特别是 - 将回复的消息与其引用的原始消息分开)(例如,使用 Python 的email
包裹)。是否可以将电子邮件消息作为 MIME 字符串获取?
问问题
304 次
1 回答
1
我不确定这是否是您的意思,但这里是您如何从您在 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 部分分开的目录。当我在引用原始消息的消息上运行此命令时,原始消息会显示在单独的部分中。
于 2018-05-18T19:16:53.243 回答