Chapter 15 ■ IMap
285
There are also a number of flags that match items in each message’s headers. Each of them searches for a given
string in the header of the same name, except for the “send” tests, which look at the Date header:
BCC string
CC string
FROM string
HEADER name string
SUBJECT string
TO string
An IMAP message has two dates: the internal Date header specified by the sender, which is called its send date,
and the date at which it actually arrived at the IMAP server. (The former could obviously be a forgery; the latter is as
reliable as the IMAP server and its clock.) So there are two sets of criteria for dates, depending on the date for which
you want to query:
BEFORE 01-Jan-1970
ON 01-Jan-1970
SINCE 01-Jan-1970
SENTBEFORE 01-Jan-1970
SENTON 01-Jan-1970
SENTSINCE 01-Jan-1970
Finally, there are two search operations that refer to the text of the message itself—these are the big workhorses
that support full-text searches of the kind your users probably expect when they type into a search field in an
e-mail client:
BODY string: The message body must contain the string.
TEXT string: The entire message, either body or header, must contain the string somewhere.
See the documentation for the particular IMAP server you are using to learn whether it returns any “near miss”
matches, like those supported by modern search engines, or only exact matches for the words that you provide.
If your strings contain any characters that IMAP might consider special, try surrounding them with double
quotes, and then backslash quote any double quotes within the strings themselves:
c.search(r'TEXT "Quoth the raven, \"Nevermore.\""')
[2652L]
Note that by using a raw Python r'...' string here, I avoided having to double up the backslashes to get single
backslashes through to IMAP.
Manipulating Folders and Messages
Creating or deleting folders is performed quite simply in IMAP by providing the name of the folder:
c.create_folder('Personal')
c.delete_folder('Work')
Some IMAP servers or configurations may not permit these operations, or they may have restrictions on naming;
be sure to have error checking in place when calling them.
There are two operations that can create new e-mail messages in your IMAP account besides the “normal” means
of waiting for people to send them to you.