Package ProcImap :: Module imaplib2 :: Class IMAP4
[hide private]
[frames] | no frames]

Class IMAP4

source code

object --+
         |
        IMAP4
Known Subclasses:

Threaded IMAP4 client class.

Instantiate with:
    IMAP4(host=None, port=None, debug=None, debug_file=None)

    host       - host's name (default: localhost);
    port       - port number (default: standard IMAP4 port);
    debug      - debug level (default: 0 - no debug);
    debug_file - debug stream (default: sys.stderr).

All IMAP4rev1 commands are supported by methods of the same name.

Each command returns a tuple: (type, [data, ...]) where 'type'
is usually 'OK' or 'NO', and 'data' is either the text from the
tagged response, or untagged results from 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).

Errors raise the exception class <instance>.error("<reason>").
IMAP4 server errors raise <instance>.abort("<reason>"), which is
a sub-class of 'error'. Mailbox status changes from READ-WRITE to
READ-ONLY raise the exception class <instance>.readonly("<reason>"),
which is a sub-class of 'abort'.

"error" exceptions imply a program error.
"abort" exceptions imply the connection should be reset, and
        the command re-tried.
"readonly" exceptions imply the command should be re-tried.

All commands take two optional named arguments:
    'callback' and 'cb_arg'
If 'callback' is provided then the command is asynchronous, so after
the command is queued for transmission, the call returns immediately
with the tuple (None, None).
The result will be posted by invoking "callback" with one arg, a tuple:
    callback((result, cb_arg, None))
or, if there was a problem:
    callback((None, cb_arg, (exception class, reason)))

Otherwise the command is synchronous (waits for result). But note
that state-changing commands will both block until previous commands
have completed, and block subsequent commands until they have finished.

All (non-callback) 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 any
non-printing characters or white-space 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:
"(\Deleted)").

There is one instance variable, 'state', that is useful for tracking
whether the client needs to login to the server. If it has the
value "AUTH" after instantiating the class, then the connection
is pre-authenticated (otherwise it will be "NONAUTH"). Selecting a
mailbox changes the state to be "SELECTED", closing a mailbox changes
back to "AUTH", and once the client has logged out, the state changes
to "LOGOUT" and no further commands may be issued.

Note: to use this module, you must read the RFCs pertaining to the
IMAP4 protocol, as the semantics of the arguments to each IMAP4
command are left to the invoker, not to mention the results. Also,
most IMAP servers implement a sub-set of the commands available here.

Note also that you must call logout() to shut down threads before
discarding an instance.

Nested Classes [hide private]
  error
  abort
  readonly
Instance Methods [hide private]
 
__init__(self, host=None, port=None, debug=None, debug_file=None)
x.__init__(...) initializes x; see x.__class__.__doc__ for signature
source code
 
__getattr__(self, attr) source code
 
open(host=None, port=None)
Setup connection to remote server on "host:port" (default: localhost:standard IMAP4 port).
source code
 
open_socket(self)
Open socket choosing first address family available.
source code
 
read(self, size)
data = read(size) Read at most 'size' bytes from remote.
source code
 
send(data)
Send 'data' to remote.
source code
 
shutdown()
Close I/O established in "open".
source code
 
socket(self)
socket = socket() Return socket instance used to connect to IMAP4 server.
source code
 
recent(self, **kw)
(typ, [data]) = recent() Return most recent 'RECENT' responses if any exist, else prompt server for an update using the 'NOOP' command.
source code
 
response(self, code, **kw)
(code, [data]) = response(code) Return data for response 'code' if received, or None.
source code
 
append(self, mailbox, flags, date_time, message, **kw)
(typ, [data]) = append(mailbox, flags, date_time, message) Append message to named mailbox.
source code
 
authenticate(self, mechanism, authobject, **kw)
(typ, [data]) = authenticate(mechanism, authobject) Authenticate command - requires response processing.
source code
 
capability(self, **kw)
(typ, [data]) = capability() Fetch capabilities list from server.
source code
 
check(self, **kw)
(typ, [data]) = check() Checkpoint mailbox on server.
source code
 
close(self, **kw)
(typ, [data]) = close() Close currently selected mailbox.
source code
 
copy(self, message_set, new_mailbox, **kw)
(typ, [data]) = copy(message_set, new_mailbox) Copy 'message_set' messages onto end of 'new_mailbox'.
source code
 
create(self, mailbox, **kw)
(typ, [data]) = create(mailbox) Create new mailbox.
source code
 
delete(self, mailbox, **kw)
(typ, [data]) = delete(mailbox) Delete old mailbox.
source code
 
deleteacl(self, mailbox, who, **kw)
(typ, [data]) = deleteacl(mailbox, who) Delete the ACLs (remove any rights) set for who on mailbox.
source code
 
examine(self, mailbox='INBOX', **kw)
(typ, [data]) = examine(mailbox='INBOX', readonly=False) Select a mailbox for READ-ONLY access.
source code
 
expunge(self, **kw)
(typ, [data]) = expunge() Permanently remove deleted items from selected mailbox.
source code
 
fetch(self, message_set, message_parts, **kw)
(typ, [data, ...]) = fetch(message_set, message_parts) Fetch (parts of) messages.
source code
 
getacl(self, mailbox, **kw)
(typ, [data]) = getacl(mailbox) Get the ACLs for a mailbox.
source code
 
getannotation(self, mailbox, entry, attribute, **kw)
(typ, [data]) = getannotation(mailbox, entry, attribute) Retrieve ANNOTATIONs.
source code
 
getquota(self, root, **kw)
(typ, [data]) = getquota(root) Get the quota root's resource usage and limits.
source code
 
getquotaroot(self, mailbox, **kw)
(typ, [[QUOTAROOT responses...], [QUOTA responses...]]) = getquotaroot(mailbox) Get the list of quota roots for the named mailbox.
source code
 
idle(self, timeout=None, **kw)
"(typ, [data]) = idle(timeout=None) Put server into IDLE mode until server notifies some change, or 'timeout' (secs) occurs (default: 29 minutes), or another IMAP4 command is scheduled.
source code
 
list(self, directory='""', pattern='*', **kw)
(typ, [data]) = list(directory='""', pattern='*') List mailbox names in directory matching pattern.
source code
 
login(self, user, password, **kw)
(typ, [data]) = login(user, password) Identify client using plaintext password.
source code
 
login_cram_md5(self, user, password, **kw)
(typ, [data]) = login_cram_md5(user, password) Force use of CRAM-MD5 authentication.
source code
 
_CRAM_MD5_AUTH(self, challenge)
Authobject to use with CRAM-MD5 authentication.
source code
 
logout(self, **kw)
(typ, [data]) = logout() Shutdown connection to server.
source code
 
lsub(self, directory='""', pattern='*', **kw)
(typ, [data, ...]) = lsub(directory='""', pattern='*') List 'subscribed' mailbox names in directory matching pattern.
source code
 
myrights(self, mailbox)
(typ, [data]) = myrights(mailbox) Show my ACLs for a mailbox (i.e.
source code
 
namespace(self, **kw)
(typ, [data, ...]) = namespace() Returns IMAP namespaces ala rfc2342.
source code
 
noop(self, **kw)
(typ, [data]) = noop() Send NOOP command.
source code
 
partial(self, message_num, message_part, start, length, **kw)
(typ, [data, ...]) = partial(message_num, message_part, start, length) Fetch truncated part of a message.
source code
 
proxyauth(self, user, **kw)
(typ, [data]) = proxyauth(user) Assume authentication as 'user'.
source code
 
rename(self, oldmailbox, newmailbox, **kw)
(typ, [data]) = rename(oldmailbox, newmailbox) Rename old mailbox name to new.
source code
 
search(self, charset, *criteria, **kw)
(typ, [data]) = search(charset, criterion, ...) Search mailbox for matching messages.
source code
 
select(self, mailbox='INBOX', readonly=False, **kw)
(typ, [data]) = select(mailbox='INBOX', readonly=False) Select a mailbox.
source code
 
setacl(self, mailbox, who, what, **kw)
(typ, [data]) = setacl(mailbox, who, what) Set a mailbox acl.
source code
 
setannotation(self, *args, **kw)
(typ, [data]) = setannotation(mailbox[, entry, attribute]+) Set ANNOTATIONs.
source code
 
setquota(self, root, limits, **kw)
(typ, [data]) = setquota(root, limits) Set the quota root's resource limits.
source code
 
sort(self, sort_criteria, charset, *search_criteria, **kw)
(typ, [data]) = sort(sort_criteria, charset, search_criteria, ...) IMAP4rev1 extension SORT command.
source code
 
status(self, mailbox, names, **kw)
(typ, [data]) = status(mailbox, names) Request named status conditions for mailbox.
source code
 
store(self, message_set, command, flags, **kw)
(typ, [data]) = store(message_set, command, flags) Alters flag dispositions for messages in mailbox.
source code
 
subscribe(self, mailbox, **kw)
(typ, [data]) = subscribe(mailbox) Subscribe to new mailbox.
source code
 
thread(self, threading_algorithm, charset, *search_criteria, **kw)
(type, [data]) = thread(threading_alogrithm, charset, search_criteria, ...) IMAPrev1 extension THREAD command.
source code
 
uid(self, command, *args, **kw)
(typ, [data]) = uid(command, arg, ...) Execute "command arg ..." with messages identified by UID, rather than message number.
source code
 
unsubscribe(self, mailbox, **kw)
(typ, [data]) = unsubscribe(mailbox) Unsubscribe from old mailbox.
source code
 
xatom(self, name, *args, **kw)
(typ, [data]) = xatom(name, arg, ...) Allow simple extension commands notified by server in CAPABILITY response.
source code
 
_append_untagged(self, typ, dat) source code
 
_check_bye(self) source code
 
_checkquote(self, arg) source code
 
_command(self, name, *args, **kw) source code
 
_command_complete(self, rqb, kw) source code
 
_command_completer(self, (response, cb_arg, error)) source code
 
_deliver_dat(self, typ, dat, kw) source code
 
_deliver_exc(self, exc, dat, kw) source code
 
_end_idle(self) source code
 
_match(self, cre, s) source code
 
_put_response(self, resp) source code
 
_quote(self, arg) source code
 
_request_pop(self, name, data) source code
 
_request_push(self, tag=None, name=None, **kw) source code
 
_simple_command(self, name, *args, **kw) source code
 
_untagged_response(self, typ, dat, name) source code
 
_close_threads(self) source code
 
_handler(self) source code
 
_reader(self) source code
 
_writer(self) source code
 
_init_debug(self, debug=None, debug_file=None) source code
 
_dump_ur(self, lvl) source code
 
_log(self, lvl, line) source code
 
_mesg(self, s, tn=None, secs=None) source code
 
_print_log(self) source code

Inherited from object: __delattr__, __getattribute__, __hash__, __new__, __reduce__, __reduce_ex__, __repr__, __setattr__, __str__

Class Variables [hide private]
  continuation_cre = re.compile(r'\+( (?P<data>.*))?')
  literal_cre = re.compile(r'.*\{(?P<size>\d+)\}$')
  mapCRLF_cre = re.compile(r'\r\n|\r|\n')
  mustquote_cre = re.compile(r'[^\w!#\$%&\'\*\+,\.:;<=>\?\^`\|~-]')
  response_code_cre = re.compile(r'\[(?P<type>[A-Z-]+)( (?P<data...
  untagged_response_cre = re.compile(r'\* (?P<type>[A-Z-]+)( (?P...
  untagged_status_cre = re.compile(r'\* (?P<data>\d+) (?P<type>[...
Properties [hide private]

Inherited from object: __class__

Method Details [hide private]

__init__(self, host=None, port=None, debug=None, debug_file=None)
(Constructor)

source code 

x.__init__(...) initializes x; see x.__class__.__doc__ for signature

Overrides: object.__init__
(inherited documentation)

open(host=None, port=None)

source code 
Setup connection to remote server on "host:port"
    (default: localhost:standard IMAP4 port).
This connection will be used by the routines:
    read, send, shutdown, socket.

recent(self, **kw)

source code 

(typ, [data]) = recent() Return most recent 'RECENT' responses if any exist, else prompt server for an update using the 'NOOP' command. 'data' is None if no new messages, else list of RECENT responses, most recent last.

response(self, code, **kw)

source code 

(code, [data]) = response(code) Return data for response 'code' if received, or None. Old value for response 'code' is cleared.

append(self, mailbox, flags, date_time, message, **kw)

source code 

(typ, [data]) = append(mailbox, flags, date_time, message) Append message to named mailbox. All args except `message' can be None.

authenticate(self, mechanism, authobject, **kw)

source code 
(typ, [data]) = authenticate(mechanism, authobject)
Authenticate command - requires response processing.

'mechanism' specifies which authentication mechanism is to
be used - it must appear in <instance>.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.

close(self, **kw)

source code 

(typ, [data]) = close() Close currently selected mailbox.

Deleted messages are removed from writable mailbox. This is the recommended command before 'LOGOUT'.

examine(self, mailbox='INBOX', **kw)

source code 

(typ, [data]) = examine(mailbox='INBOX', readonly=False) Select a mailbox for READ-ONLY access. (Flushes all untagged responses.) 'data' is count of messages in mailbox ('EXISTS' response). Mandated responses are ('FLAGS', 'EXISTS', 'RECENT', 'UIDVALIDITY'), so other responses should be obtained via "response('FLAGS')" etc.

expunge(self, **kw)

source code 

(typ, [data]) = expunge() Permanently remove deleted items from selected mailbox. Generates 'EXPUNGE' response for each deleted message. 'data' is list of 'EXPUNGE'd message numbers in order received.

fetch(self, message_set, message_parts, **kw)

source code 

(typ, [data, ...]) = fetch(message_set, message_parts) Fetch (parts of) messages. 'message_parts' should be a string of selected parts enclosed in parentheses, eg: "(UID BODY[TEXT])". 'data' are tuples of message part envelope and data, followed by a string containing the trailer.

getquota(self, root, **kw)

source code 

(typ, [data]) = getquota(root) Get the quota root's resource usage and limits. (Part of the IMAP4 QUOTA extension defined in rfc2087.)

list(self, directory='""', pattern='*', **kw)

source code 

(typ, [data]) = list(directory='""', pattern='*') List mailbox names in directory matching pattern. 'data' is list of LIST responses.

NB: for 'pattern': % matches all except separator ( so LIST "" "%" returns names at root) * matches all (so LIST "" "*" returns whole directory tree from root)

login(self, user, password, **kw)

source code 

(typ, [data]) = login(user, password) Identify client using plaintext password. NB: 'password' will be quoted.

logout(self, **kw)

source code 

(typ, [data]) = logout() Shutdown connection to server. Returns server 'BYE' response.

lsub(self, directory='""', pattern='*', **kw)

source code 

(typ, [data, ...]) = lsub(directory='""', pattern='*') List 'subscribed' mailbox names in directory matching pattern. 'data' are tuples of message part envelope and data.

myrights(self, mailbox)

source code 

(typ, [data]) = myrights(mailbox) Show my ACLs for a mailbox (i.e. the rights that I have on mailbox).

partial(self, message_num, message_part, start, length, **kw)

source code 

(typ, [data, ...]) = partial(message_num, message_part, start, length) Fetch truncated part of a message. 'data' is tuple of message part envelope and data. NB: obsolete.

proxyauth(self, user, **kw)

source code 

(typ, [data]) = proxyauth(user) Assume authentication as 'user'. (Allows an authorised administrator to proxy into any user's mailbox.)

search(self, charset, *criteria, **kw)

source code 

(typ, [data]) = search(charset, criterion, ...) Search mailbox for matching messages. 'data' is space separated list of matching message numbers.

select(self, mailbox='INBOX', readonly=False, **kw)

source code 

(typ, [data]) = select(mailbox='INBOX', readonly=False) Select a mailbox. (Flushes all untagged responses.) 'data' is count of messages in mailbox ('EXISTS' response). Mandated responses are ('FLAGS', 'EXISTS', 'RECENT', 'UIDVALIDITY'), so other responses should be obtained via "response('FLAGS')" etc.

uid(self, command, *args, **kw)

source code 
(typ, [data]) = uid(command, arg, ...)
Execute "command arg ..." with messages identified by UID,
    rather than message number.
Returns response appropriate to 'command'.

xatom(self, name, *args, **kw)

source code 

(typ, [data]) = xatom(name, arg, ...) Allow simple extension commands notified by server in CAPABILITY response. Assumes extension command 'name' is legal in current state. Returns response appropriate to extension command 'name'.


Class Variable Details [hide private]

response_code_cre

Value:
re.compile(r'\[(?P<type>[A-Z-]+)( (?P<data>[^\]]*))?\]')

untagged_response_cre

Value:
re.compile(r'\* (?P<type>[A-Z-]+)( (?P<data>.*))?')

untagged_status_cre

Value:
re.compile(r'\* (?P<data>\d+) (?P<type>[A-Z-]+)( (?P<data2>.*))?')