This module defines three classes, IMAP4, IMAP4_SSL and IMAP4_stream, which encapsulate a connection to an IMAP4 server and implement a large subset of the IMAP4rev1 client protocol as defined in RFC 2060. It is backward compatible with IMAP4 (RFC 1730) servers, but note that the STATUS command is not supported in IMAP4.
Three classes are provided by the imaplib module, IMAP4 is the base class:
Three exceptions are defined as attributes of the IMAP4 class:
There’s also a subclass for secure connections:
The second subclass allows for connections created by a child process:
This is a subclass derived from IMAP4 that connects to the stdin/stdout file descriptors created by passing command to os.popen2().
New in version 2.3.
The following utility functions are defined:
Note that IMAP4 message numbers change as the mailbox changes; in particular, after an EXPUNGE command performs deletions the remaining messages are renumbered. So it is highly advisable to use UIDs instead, with the UID command.
At the end of the module, there is a test section that contains a more extensive example of usage.
See also
Documents describing the protocol, and sources and binaries for servers implementing it, can all be found at the University of Washington’s IMAP Information Center (http://www.washington.edu/imap/).
All IMAP4rev1 commands are represented by methods of the same name, either upper-case or lower-case.
All arguments to commands are converted to strings, except for AUTHENTICATE, and the last argument to APPEND which is passed as an IMAP4 literal. If necessary (the string contains IMAP4 protocol-sensitive characters and isn’t enclosed with either parentheses or double quotes) each string is quoted. However, the password argument to the LOGIN command is always quoted. If you want to avoid having an argument string quoted (eg: the flags argument to STORE) then enclose the string in parentheses (eg: r'(\Deleted)').
Each command returns a tuple: (type, [data, ...]) where type is usually 'OK' or 'NO', and data is either the text from the command response, or mandated results from the command. Each data is either a string, or a tuple. If a tuple, then the first part is the header of the response, and the second part contains the data (ie: ‘literal’ value).
The message_set options to commands below is a string specifying one or more messages to be acted upon. It may be a simple message number ('1'), a range of message numbers ('2:4'), or a group of non-contiguous ranges separated by commas ('1:3,6:9'). A range can contain an asterisk to indicate an infinite upper bound ('3:*').
An IMAP4 instance has the following methods:
Authenticate command — requires response processing.
mechanism specifies which authentication mechanism is to be used - it should appear in the instance variable capabilities in the form AUTH=mechanism.
authobject must be a callable object:
data = authobject(response)
It will be called to process server continuation responses. It should return data that will be encoded and sent to server. It should return None if the client abort response * should be sent instead.
Delete the ACLs (remove any rights) set for who on mailbox.
New in version 2.4.
Retrieve the specified ANNOTATIONs for mailbox. The method is non-standard, but is supported by the Cyrus server.
New in version 2.5.
Get the quota root‘s resource usage and limits. This method is part of the IMAP4 QUOTA extension defined in rfc2087.
New in version 2.3.
Get the list of quota roots for the named mailbox. This method is part of the IMAP4 QUOTA extension defined in rfc2087.
New in version 2.3.
Force use of CRAM-MD5 authentication when identifying the client to protect the password. Will only work if the server CAPABILITY response includes the phrase AUTH=CRAM-MD5.
New in version 2.3.
Show my ACLs for a mailbox (i.e. the rights that I have on mailbox).
New in version 2.4.
Returns IMAP namespaces as defined in RFC2342.
New in version 2.3.
Assume authentication as user. Allows an authorised administrator to proxy into any user’s mailbox.
New in version 2.3.
Search mailbox for matching messages. charset may be None, in which case no CHARSET will be specified in the request to the server. The IMAP protocol requires that at least one criterion be specified; an exception will be raised when the server returns an error.
Example:
# M is a connected IMAP4 instance...
typ, msgnums = M.search(None, 'FROM', '"LDJ"')
# or:
typ, msgnums = M.search(None, '(FROM "LDJ")')
Set ANNOTATIONs for mailbox. The method is non-standard, but is supported by the Cyrus server.
New in version 2.5.
Set the quota root‘s resource limits. This method is part of the IMAP4 QUOTA extension defined in rfc2087.
New in version 2.3.
The sort command is a variant of search with sorting semantics for the results. Returned data contains a space separated list of matching message numbers.
Sort has two arguments before the search_criterion argument(s); a parenthesized list of sort_criteria, and the searching charset. Note that unlike search, the searching charset argument is mandatory. There is also a uid sort command which corresponds to sort the way that uid search corresponds to search. The sort command first searches the mailbox for messages that match the given searching criteria using the charset argument for the interpretation of strings in the searching criteria. It then returns the numbers of matching messages.
This is an IMAP4rev1 extension command.
Alters flag dispositions for messages in mailbox. command is specified by section 6.4.6 of RFC 2060 as being one of “FLAGS”, “+FLAGS”, or “-FLAGS”, optionally with a suffix of “.SILENT”.
For example, to set the delete flag on all messages:
typ, data = M.search(None, 'ALL')
for num in data[0].split():
M.store(num, '+FLAGS', '\\Deleted')
M.expunge()
The thread command is a variant of search with threading semantics for the results. Returned data contains a space separated list of thread members.
Thread members consist of zero or more messages numbers, delimited by spaces, indicating successive parent and child.
Thread has two arguments before the search_criterion argument(s); a threading_algorithm, and the searching charset. Note that unlike search, the searching charset argument is mandatory. There is also a uid thread command which corresponds to thread the way that uid search corresponds to search. The thread command first searches the mailbox for messages that match the given searching criteria using the charset argument for the interpretation of strings in the searching criteria. It then returns the matching messages threaded according to the specified threading algorithm.
This is an IMAP4rev1 extension command.
New in version 2.4.
Instances of IMAP4_SSL have just one additional method:
The following attributes are defined on instances of IMAP4:
Here is a minimal example (without error checking) that opens a mailbox and retrieves and prints all messages:
import getpass, imaplib
M = imaplib.IMAP4()
M.login(getpass.getuser(), getpass.getpass())
M.select()
typ, data = M.search(None, 'ALL')
for num in data[0].split():
typ, data = M.fetch(num, '(RFC822)')
print 'Message %s\n%s\n' % (num, data[0][1])
M.close()
M.logout()