1 \section{\module{imaplib
} ---
4 \declaremodule{standard
}{imaplib
}
5 \modulesynopsis{IMAP4 protocol client (requires sockets).
}
6 \moduleauthor{Piers Lauder
}{piers@communitysolutions.com.au
}
7 \sectionauthor{Piers Lauder
}{piers@communitysolutions.com.au
}
9 % Based on HTML documentation by Piers Lauder <piers@communitysolutions.com.au>;
10 % converted by Fred L. Drake, Jr. <fdrake@acm.org>.
11 % Revised by ESR, January 2000.
12 % Changes for IMAP4_SSL by Tino Lange <Tino.Lange@isg.de>, March 2002
13 % Changes for IMAP4_stream by Piers Lauder <piers@communitysolutions.com.au>, November 2002
15 \indexii{IMAP4
}{protocol
}
16 \indexii{IMAP4_SSL
}{protocol
}
17 \indexii{IMAP4_stream
}{protocol
}
19 This module defines three classes,
\class{IMAP4
},
\class{IMAP4_SSL
} and
\class{IMAP4_stream
}, which encapsulate a
20 connection to an IMAP4 server and implement a large subset of the
21 IMAP4rev1 client protocol as defined in
\rfc{2060}. It is backward
22 compatible with IMAP4 (
\rfc{1730}) servers, but note that the
23 \samp{STATUS
} command is not supported in IMAP4.
25 Three classes are provided by the
\module{imaplib
} module,
\class{IMAP4
} is the base class:
27 \begin{classdesc
}{IMAP4
}{\optional{host
\optional{, port
}}}
28 This class implements the actual IMAP4 protocol. The connection is
29 created and protocol version (IMAP4 or IMAP4rev1) is determined when
30 the instance is initialized.
31 If
\var{host
} is not specified,
\code{''
} (the local host) is used.
32 If
\var{port
} is omitted, the standard IMAP4 port (
143) is used.
35 Three exceptions are defined as attributes of the
\class{IMAP4
} class:
37 \begin{excdesc
}{IMAP4.error
}
38 Exception raised on any errors. The reason for the exception is
39 passed to the constructor as a string.
42 \begin{excdesc
}{IMAP4.abort
}
43 IMAP4 server errors cause this exception to be raised. This is a
44 sub-class of
\exception{IMAP4.error
}. Note that closing the instance
45 and instantiating a new one will usually allow recovery from this
49 \begin{excdesc
}{IMAP4.readonly
}
50 This exception is raised when a writable mailbox has its status changed by the server. This is a
51 sub-class of
\exception{IMAP4.error
}. Some other client now has write permission,
52 and the mailbox will need to be re-opened to re-obtain write permission.
55 There's also a subclass for secure connections:
57 \begin{classdesc
}{IMAP4_SSL
}{\optional{host
\optional{, port
\optional{, keyfile
\optional{, certfile
}}}}}
58 This is a subclass derived from
\class{IMAP4
} that connects over an SSL encrypted socket
59 (to use this class you need a socket module that was compiled with SSL support).
60 If
\var{host
} is not specified,
\code{''
} (the local host) is used.
61 If
\var{port
} is omitted, the standard IMAP4-over-SSL port (
993) is used.
62 \var{keyfile
} and
\var{certfile
} are also optional - they can contain a PEM formatted
63 private key and certificate chain file for the SSL connection.
66 The second subclass allows for connections created by a child process:
68 \begin{classdesc
}{IMAP4_stream
}{command
}
69 This is a subclass derived from
\class{IMAP4
} that connects
70 to the
\code{stdin/stdout
} file descriptors created by passing
\var{command
} to
\code{os.popen2()
}.
74 The following utility functions are defined:
76 \begin{funcdesc
}{Internaldate2tuple
}{datestr
}
77 Converts an IMAP4 INTERNALDATE string to Coordinated Universal
78 Time. Returns a
\refmodule{time
} module tuple.
81 \begin{funcdesc
}{Int2AP
}{num
}
82 Converts an integer into a string representation using characters
83 from the set
[\code{A
} ..
\code{P
}].
86 \begin{funcdesc
}{ParseFlags
}{flagstr
}
87 Converts an IMAP4
\samp{FLAGS
} response to a tuple of individual
91 \begin{funcdesc
}{Time2Internaldate
}{date_time
}
92 Converts a
\refmodule{time
} module tuple to an IMAP4
93 \samp{INTERNALDATE
} representation. Returns a string in the form:
94 \code{"DD-Mmm-YYYY HH:MM:SS +HHMM"
} (including double-quotes).
98 Note that IMAP4 message numbers change as the mailbox changes; in
99 particular, after an
\samp{EXPUNGE
} command performs deletions the
100 remaining messages are renumbered. So it is highly advisable to use
101 UIDs instead, with the UID command.
103 At the end of the module, there is a test section that contains a more
104 extensive example of usage.
107 \seetext{Documents describing the protocol, and sources and binaries
108 for servers implementing it, can all be found at the
109 University of Washington's
\emph{IMAP Information Center
}
110 (
\url{http://www.cac.washington.edu/imap/
}).
}
114 \subsection{IMAP4 Objects
\label{imap4-objects
}}
116 All IMAP4rev1 commands are represented by methods of the same name,
117 either upper-case or lower-case.
119 All arguments to commands are converted to strings, except for
120 \samp{AUTHENTICATE
}, and the last argument to
\samp{APPEND
} which is
121 passed as an IMAP4 literal. If necessary (the string contains IMAP4
122 protocol-sensitive characters and isn't enclosed with either
123 parentheses or double quotes) each string is quoted. However, the
124 \var{password
} argument to the
\samp{LOGIN
} command is always quoted.
125 If you want to avoid having an argument string quoted
126 (eg: the
\var{flags
} argument to
\samp{STORE
}) then enclose the string in
127 parentheses (eg:
\code{r'(
\e Deleted)'
}).
129 Each command returns a tuple:
\code{(
\var{type
},
[\var{data
},
130 ...
])
} where
\var{type
} is usually
\code{'OK'
} or
\code{'NO'
},
131 and
\var{data
} is either the text from the command response, or
132 mandated results from the command. Each
\var{data
}
133 is either a string, or a tuple. If a tuple, then the first part
134 is the header of the response, and the second part contains
135 the data (ie: 'literal' value).
137 An
\class{IMAP4
} instance has the following methods:
140 \begin{methoddesc
}{append
}{mailbox, flags, date_time, message
}
141 Append message to named mailbox.
144 \begin{methoddesc
}{authenticate
}{func
}
145 Authenticate command --- requires response processing. This is
146 currently unimplemented, and raises an exception.
149 \begin{methoddesc
}{check
}{}
150 Checkpoint mailbox on server.
153 \begin{methoddesc
}{close
}{}
154 Close currently selected mailbox. Deleted messages are removed from
155 writable mailbox. This is the recommended command before
159 \begin{methoddesc
}{copy
}{message_set, new_mailbox
}
160 Copy
\var{message_set
} messages onto end of
\var{new_mailbox
}.
163 \begin{methoddesc
}{create
}{mailbox
}
164 Create new mailbox named
\var{mailbox
}.
167 \begin{methoddesc
}{delete
}{mailbox
}
168 Delete old mailbox named
\var{mailbox
}.
171 \begin{methoddesc
}{expunge
}{}
172 Permanently remove deleted items from selected mailbox. Generates an
173 \samp{EXPUNGE
} response for each deleted message. Returned data
174 contains a list of
\samp{EXPUNGE
} message numbers in order
178 \begin{methoddesc
}{fetch
}{message_set, message_parts
}
179 Fetch (parts of) messages.
\var{message_parts
} should be
180 a string of message part names enclosed within parentheses,
181 eg:
\samp{"(UID BODY
[TEXT
])"
}. Returned data are tuples
182 of message part envelope and data.
185 \begin{methoddesc
}{getacl
}{mailbox
}
186 Get the
\samp{ACL
}s for
\var{mailbox
}.
187 The method is non-standard, but is supported by the
\samp{Cyrus
} server.
190 \begin{methoddesc
}{getquota
}{root
}
191 Get the
\samp{quota
} \var{root
}'s resource usage and limits.
192 This method is part of the IMAP4 QUOTA extension defined in rfc2087.
196 \begin{methoddesc
}{getquotaroot
}{mailbox
}
197 Get the list of
\samp{quota
} \samp{roots
} for the named
\var{mailbox
}.
198 This method is part of the IMAP4 QUOTA extension defined in rfc2087.
202 \begin{methoddesc
}{list
}{\optional{directory
\optional{, pattern
}}}
203 List mailbox names in
\var{directory
} matching
204 \var{pattern
}.
\var{directory
} defaults to the top-level mail
205 folder, and
\var{pattern
} defaults to match anything. Returned data
206 contains a list of
\samp{LIST
} responses.
209 \begin{methoddesc
}{login
}{user, password
}
210 Identify the client using a plaintext password.
211 The
\var{password
} will be quoted.
214 \begin{methoddesc
}{login_cram_md5
}{user, password
}
215 Force use of
\samp{CRAM-MD5
} authentication when identifying the client to protect the password.
216 Will only work if the server
\samp{CAPABILITY
} response includes the phrase
\samp{AUTH=CRAM-MD5
}.
220 \begin{methoddesc
}{logout
}{}
221 Shutdown connection to server. Returns server
\samp{BYE
} response.
224 \begin{methoddesc
}{lsub
}{\optional{directory
\optional{, pattern
}}}
225 List subscribed mailbox names in directory matching pattern.
226 \var{directory
} defaults to the top level directory and
227 \var{pattern
} defaults to match any mailbox.
228 Returned data are tuples of message part envelope and data.
231 \begin{methoddesc
}{noop
}{}
232 Send
\samp{NOOP
} to server.
235 \begin{methoddesc
}{open
}{host, port
}
236 Opens socket to
\var{port
} at
\var{host
}.
237 The connection objects established by this method
238 will be used in the
\code{read
},
\code{readline
},
\code{send
}, and
\code{shutdown
} methods.
239 You may override this method.
242 \begin{methoddesc
}{partial
}{message_num, message_part, start, length
}
243 Fetch truncated part of a message.
244 Returned data is a tuple of message part envelope and data.
247 \begin{methoddesc
}{proxyauth
}{user
}
248 Assume authentication as
\var{user
}.
249 Allows an authorised administrator to proxy into any user's mailbox.
253 \begin{methoddesc
}{read
}{size
}
254 Reads
\var{size
} bytes from the remote server.
255 You may override this method.
258 \begin{methoddesc
}{readline
}{}
259 Reads one line from the remote server.
260 You may override this method.
263 \begin{methoddesc
}{recent
}{}
264 Prompt server for an update. Returned data is
\code{None
} if no new
265 messages, else value of
\samp{RECENT
} response.
268 \begin{methoddesc
}{rename
}{oldmailbox, newmailbox
}
269 Rename mailbox named
\var{oldmailbox
} to
\var{newmailbox
}.
272 \begin{methoddesc
}{response
}{code
}
273 Return data for response
\var{code
} if received, or
274 \code{None
}. Returns the given code, instead of the usual type.
277 \begin{methoddesc
}{search
}{charset, criterium
\optional{, ...
}}
278 Search mailbox for matching messages. Returned data contains a space
279 separated list of matching message numbers.
\var{charset
} may be
280 \code{None
}, in which case no
\samp{CHARSET
} will be specified in the
281 request to the server. The IMAP protocol requires that at least one
282 criterium be specified; an exception will be raised when the server
288 # M is a connected IMAP4 instance...
289 msgnums = M.search(None, 'FROM', '"LDJ"')
292 msgnums = M.search(None, '(FROM "LDJ")')
296 \begin{methoddesc
}{select
}{\optional{mailbox
\optional{, readonly
}}}
297 Select a mailbox. Returned data is the count of messages in
298 \var{mailbox
} (
\samp{EXISTS
} response). The default
\var{mailbox
}
299 is
\code{'INBOX'
}. If the
\var{readonly
} flag is set, modifications
300 to the mailbox are not allowed.
303 \begin{methoddesc
}{send
}{data
}
304 Sends
\code{data
} to the remote server.
305 You may override this method.
308 \begin{methoddesc
}{setacl
}{mailbox, who, what
}
309 Set an
\samp{ACL
} for
\var{mailbox
}.
310 The method is non-standard, but is supported by the
\samp{Cyrus
} server.
313 \begin{methoddesc
}{setquota
}{root, limits
}
314 Set the
\samp{quota
} \var{root
}'s resource
\var{limits
}.
315 This method is part of the IMAP4 QUOTA extension defined in rfc2087.
319 \begin{methoddesc
}{shutdown
}{}
320 Close connection established in
\code{open
}.
321 You may override this method.
324 \begin{methoddesc
}{socket
}{}
325 Returns socket instance used to connect to server.
328 \begin{methoddesc
}{sort
}{sort_criteria, charset, search_criterium
\optional{, ...
}}
329 The
\code{sort
} command is a variant of
\code{search
} with sorting semantics for
330 the results. Returned data contains a space
331 separated list of matching message numbers.
333 Sort has two arguments before the
\var{search_criterium
}
334 argument(s); a parenthesized list of
\var{sort_criteria
}, and the searching
\var{charset
}.
335 Note that unlike
\code{search
}, the searching
\var{charset
} argument is mandatory.
336 There is also a
\code{uid sort
} command which corresponds to
\code{sort
} the way
337 that
\code{uid search
} corresponds to
\code{search
}.
338 The
\code{sort
} command first searches the mailbox for messages that
339 match the given searching criteria using the charset argument for
340 the interpretation of strings in the searching criteria. It then
341 returns the numbers of matching messages.
343 This is an
\samp{IMAP4rev1
} extension command.
346 \begin{methoddesc
}{status
}{mailbox, names
}
347 Request named status conditions for
\var{mailbox
}.
350 \begin{methoddesc
}{store
}{message_set, command, flag_list
}
351 Alters flag dispositions for messages in mailbox.
354 \begin{methoddesc
}{subscribe
}{mailbox
}
355 Subscribe to new mailbox.
358 \begin{methoddesc
}{uid
}{command, arg
\optional{, ...
}}
359 Execute command args with messages identified by UID, rather than
360 message number. Returns response appropriate to command. At least
361 one argument must be supplied; if none are provided, the server will
362 return an error and an exception will be raised.
365 \begin{methoddesc
}{unsubscribe
}{mailbox
}
366 Unsubscribe from old mailbox.
369 \begin{methoddesc
}{xatom
}{name
\optional{, arg
\optional{, ...
}}}
370 Allow simple extension commands notified by server in
371 \samp{CAPABILITY
} response.
375 Instances of
\class{IMAP4_SSL
} have just one additional method:
377 \begin{methoddesc
}{ssl
}{}
378 Returns SSLObject instance used for the secure connection with the server.
382 The following attributes are defined on instances of
\class{IMAP4
}:
385 \begin{memberdesc
}{PROTOCOL_VERSION
}
386 The most recent supported protocol in the
387 \samp{CAPABILITY
} response from the server.
390 \begin{memberdesc
}{debug
}
391 Integer value to control debugging output. The initialize value is
392 taken from the module variable
\code{Debug
}. Values greater than
393 three trace each command.
397 \subsection{IMAP4 Example
\label{imap4-example
}}
399 Here is a minimal example (without error checking) that opens a
400 mailbox and retrieves and prints all messages:
403 import getpass, imaplib
406 M.login(getpass.getuser(), getpass.getpass())
408 typ, data = M.search(None, 'ALL')
409 for num in data
[0].split():
410 typ, data = M.fetch(num, '(RFC822)')
411 print 'Message
%s\n%s\n' % (num, data[0][1])