通过Python在IMAP中自定义标记消息
有没有办法用Python给IMAP文件夹里的邮件加上自定义标签呢?比如“汤姆的邮件”、“约翰的婚礼杂事”等等?
2 个回答
1
你可以使用 imap_tools 这个包:
https://pypi.org/project/imap-tools/
from imap_tools import MailBox, Q
with MailBox('imap.mail.com').login('test@mail.com', 'pwd', initial_folder='INBOX') as mailbox:
# FLAG unseen messages in current folder as Answered and Flagged, *in bulk.
flags = (imap_tools.StandardMessageFlags.ANSWERED, imap_tools.StandardMessageFlags.FLAGGED)
mailbox.flag(mailbox.fetch('(UNSEEN)'), flags, True)
关于如何使用关键字标准来设置自定义标记:
https://github.com/ikvk/imap_tools/blob/master/examples/keyword_criteria_and_custom_flags.py
5
Cyrus IMAP 服务器支持用户自定义的消息标记(也就是标签、关键词),你可以使用Alpine 邮件客户端来试验这些标签。在Alpine中,选择 (S)etup
-> (C)onfig
,然后向下滚动到 keywords
部分,输入你想要的标记名称列表。
如果你想用Python来设置消息标记,可以使用标准的imaplib模块。下面是一个设置消息标记的例子:
import imaplib
im = imaplib.IMAP4(hostname)
im.login(user, password)
im.select('INBOX')
# you can use im.search() to obtain message ids
msg_ids = '1, 4, 7'
labels = ['foo', 'bar', 'baz']
# add the flags to the message
im.store(msg_ids, '+FLAGS', '(%s)' % ' '.join(labels))
# fetch and print to verify the flags
print im.fetch(ids, '(FLAGS)')
im.close()
im.logout()
需要注意的是,发送到服务器的标记不能包含空格。如果你发送 +FLAGS (foo bar)
到服务器,这会设置两个标记 foo
和 bar
。像Alpine这样的客户端允许你输入带有空格的标记,但它只会把最后一个没有空格的部分发送到服务器——它把这个当作一个唯一的标识符。如果你指定的标记是 abc 123
,它会在消息上设置 123
,并在消息视图中显示 abc
。