在macOS上用Python程序访问邮件的API

3 投票
3 回答
6943 浏览
提问于 2025-04-17 10:49

我想用Python程序来访问Mac OS X系统上所有通过内置的“Mail.app”程序收到的邮件。请问有没有简单易用的接口可以访问这个程序存储的邮件?我觉得这可能不仅仅是文本格式,可能会更复杂一些。谢谢。

3 个回答

1

用这个代替:

fname = glob.glob('./mails/**/*.emlx', recursive = True)
    msg = emlx.read(fname)
    print(msg.headers['Subject'])

路径字符串中的 /**/ 就像是一个通配符,可以匹配任何内容。

11

截至2020年,你可以使用Python emlx库

pip install emlx

示例代码:

import emlx
import glob

for filepath in glob.iglob("/Users/<username>/Library/Mail/**/*.emlx", recursive=True):
     m = emlx.read(filepath)

在一条消息m上,你可以进行各种操作:

>>> m.headers
{'Subject': 'Re: Emlx library ✉️',
 'From': 'Michael <michael@example.com>',
 'Date': 'Thu, 30 Jan 2020 20:25:43 +0100',
 'Content-Type': 'text/plain; charset=utf-8',
 ...}
>>> m.headers['Subject']
'Re: Emlx library ✉️'
>>> m.plist
{'color': '000000',
 'conversation-id': 12345,
 'date-last-viewed': 1580423184,
 'flags': {...}
 ...}
>>> m.flags
{'read': True, 'answered': True, 'attachment_count': 2}

如果你需要速度,你可以只解析plistflags

>>> m = emlx.read(filepath, plist_only=True)
5

Mail.app把邮件存储为.emlx文件,这种格式我知道的并没有详细说明。不过,你可以把.emlx文件转换成标准的mbox格式(可以使用这个工具),然后再用mailbox模块来处理这些文件。

撰写回答