Is there a way to tag messages in IMAP folder with Python to custome tag? like Toms mail, john's weeding crap etc etc?
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.
To set the message flags from Python you can use the standard imaplib module. Below is an example of setting flags on a message:
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()
One thing to keep in mind is that the flags sent to the server do not contain spaces. If you send +FLAGS (foo bar)
to the server, this will set two flags foo
and bar
. Clients like Alpine will let you enter flags with spaces in them, but will only send the last non-space part to the server -- it treats this like a unique identifier. If you specify the flag abc 123
it will set the 123
on the message and display abc
in the message view.