通过python在IMAP中自定义标记消息

Max*_*Max 1 python imap

有没有办法用 Python 标记 IMAP 文件夹中的消息以自定义标记?像汤姆斯邮件,约翰的除草废话等等?

sam*_*ias 5

The Cyrus IMAP server supports user-defined message flags (aka tags, labels, keywords), and you can use the Alpine mail client for experimentation with labels. In Alpine choose (S)etup -> (C)onfig, scroll down to the keywords section and enter your list of desired flag names.

要从 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()
Run Code Online (Sandbox Code Playgroud)

要记住的一件事是发送到服务器的标志不包含空格。如果您发送+FLAGS (foo bar)到服务器,这将设置两个标志foobar. 像 Alpine 这样的客户端会让你输入带有空格的标志,但只会将最后一个非空格部分发送到服务器——它把它当作一个唯一的标识符。如果您指定标志abc 123,它将123在消息上设置并显示abc在消息视图中。