Public functions: Internaldate2tuple
# Author: Piers Lauder <piers@cs.su.oz.au> December 1997.
# Authentication code contributed by Donn Cave <donn@u.washington.edu> June 1998.
# String method conversion by ESR, February 2001.
# GET/SETACL contributed by Anthony Baxter <anthony@interlink.com.au> April 2001.
# IMAP4_SSL contributed by Tino Lange <Tino.Lange@isg.de> March 2002.
# GET/SETQUOTA contributed by Andreas Zeidler <az@kreativkombinat.de> June 2002.
# PROXYAUTH contributed by Rick Holbert <holbert.13@osu.edu> November 2002.
import binascii
, os
, random
, re
, socket
, sys
, time
__all__
= ["IMAP4", "IMAP4_SSL", "IMAP4_stream", "Internaldate2tuple",
"Int2AP", "ParseFlags", "Time2Internaldate"]
AllowedVersions
= ('IMAP4REV1', 'IMAP4') # Most recent first
'APPEND': ('AUTH', 'SELECTED'),
'AUTHENTICATE': ('NONAUTH',),
'CAPABILITY': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
'CREATE': ('AUTH', 'SELECTED'),
'DELETE': ('AUTH', 'SELECTED'),
'DELETEACL': ('AUTH', 'SELECTED'),
'EXAMINE': ('AUTH', 'SELECTED'),
'EXPUNGE': ('SELECTED',),
'GETACL': ('AUTH', 'SELECTED'),
'GETQUOTA': ('AUTH', 'SELECTED'),
'GETQUOTAROOT': ('AUTH', 'SELECTED'),
'MYRIGHTS': ('AUTH', 'SELECTED'),
'LIST': ('AUTH', 'SELECTED'),
'LOGOUT': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
'LSUB': ('AUTH', 'SELECTED'),
'NAMESPACE': ('AUTH', 'SELECTED'),
'NOOP': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
'PARTIAL': ('SELECTED',), # NB: obsolete
'RENAME': ('AUTH', 'SELECTED'),
'SELECT': ('AUTH', 'SELECTED'),
'SETACL': ('AUTH', 'SELECTED'),
'SETQUOTA': ('AUTH', 'SELECTED'),
'STATUS': ('AUTH', 'SELECTED'),
'SUBSCRIBE': ('AUTH', 'SELECTED'),
'UNSUBSCRIBE': ('AUTH', 'SELECTED'),
# Patterns to match server responses
Continuation
= re
.compile(r
'\+( (?P<data>.*))?')
Flags
= re
.compile(r
'.*FLAGS \((?P<flags>[^\)]*)\)')
InternalDate
= re
.compile(r
'.*INTERNALDATE "'
r
'(?P<day>[ 123][0-9])-(?P<mon>[A-Z][a-z][a-z])-(?P<year>[0-9][0-9][0-9][0-9])'
r
' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])'
r
' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])'
Literal
= re
.compile(r
'.*{(?P<size>\d+)}$')
MapCRLF
= re
.compile(r
'\r\n|\r|\n')
Response_code
= re
.compile(r
'\[(?P<type>[A-Z-]+)( (?P<data>[^\]]*))?\]')
Untagged_response
= re
.compile(r
'\* (?P<type>[A-Z-]+)( (?P<data>.*))?')
Untagged_status
= re
.compile(r
'\* (?P<data>\d+) (?P<type>[A-Z-]+)( (?P<data2>.*))?')
Instantiate with: IMAP4([host[, port]])
host - host's name (default: localhost);
port - port number (default: standard IMAP4 port).
All IMAP4rev1 commands are supported by methods of the same
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 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)").
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
"readonly" exceptions imply the command should be re-tried.
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
class error(Exception): pass # Logical errors - debug required
class abort(error
): pass # Service errors - close and retry
class readonly(abort
): pass # Mailbox status changed to READ-ONLY
mustquote
= re
.compile(r
"[^\w!#$%&'*+,.:;<=>?^`|~-]")
def __init__(self
, host
= '', port
= IMAP4_PORT
):
self
.literal
= None # A literal argument to a command
self
.tagged_commands
= {} # Tagged commands awaiting response
self
.untagged_responses
= {} # {typ: [data, ...], ...}
self
.continuation_response
= '' # Last continuation response
self
.is_readonly
= None # READ-ONLY desired state
# Create unique tag for this session,
# and compile tagged response matcher.
self
.tagpre
= Int2AP(random
.randint(0, 31999))
self
.tagre
= re
.compile(r
'(?P<tag>'
+ r
'\d+) (?P<type>[A-Z]+) (?P<data>.*)')
# Get server welcome message,
# request and store CAPABILITY response.
self
._cmd
_log
= {} # Last `_cmd_log_len' interactions
self
._mesg
('imaplib version %s' % __version__
)
self
._mesg
('new IMAP4 connection, tag=%s' % self
.tagpre
)
self
.welcome
= self
._get
_response
()
if 'PREAUTH' in self
.untagged_responses
:
elif 'OK' in self
.untagged_responses
:
raise self
.error(self
.welcome
)
self
._simple
_command
(cap
)
if not cap
in self
.untagged_responses
:
raise self
.error('no CAPABILITY response from server')
self
.capabilities
= tuple(self
.untagged_responses
[cap
][-1].upper().split())
self
._mesg
('CAPABILITIES: %r' % (self
.capabilities
,))
for version
in AllowedVersions
:
if not version
in self
.capabilities
:
self
.PROTOCOL_VERSION
= version
raise self
.error('server not IMAP4 compliant')
def __getattr__(self
, attr
):
# Allow UPPERCASE variants of IMAP4 command methods.
return getattr(self
, attr
.lower())
raise AttributeError("Unknown IMAP4 command: '%s'" % attr
)
def open(self
, host
= '', port
= IMAP4_PORT
):
"""Setup connection to remote server on "host:port"
(default: localhost:standard IMAP4 port).
This connection will be used by the routines:
read, readline, send, shutdown.
self
.sock
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
self
.sock
.connect((host
, port
))
self
.file = self
.sock
.makefile('rb')
"""Read 'size' bytes from remote."""
return self
.file.read(size
)
"""Read line from remote."""
return self
.file.readline()
"""Send data to remote."""
"""Close I/O established in "open"."""
"""Return socket instance used to connect to IMAP4 server.
socket = <instance>.socket()
"""Return most recent 'RECENT' responses if any exist,
else prompt server for an update using the 'NOOP' command.
(typ, [data]) = <instance>.recent()
'data' is None if no new messages,
else list of RECENT responses, most recent last.
typ
, dat
= self
._untagged
_response
('OK', [None], name
)
typ
, dat
= self
.noop() # Prod server for response
return self
._untagged
_response
(typ
, dat
, name
)
def response(self
, code
):
"""Return data for response 'code' if received, or None.
Old value for response 'code' is cleared.
(code, [data]) = <instance>.response(code)
return self
._untagged
_response
(code
, [None], code
.upper())
def append(self
, mailbox
, flags
, date_time
, message
):
"""Append message to named mailbox.
(typ, [data]) = <instance>.append(mailbox, flags, date_time, message)
All args except `message' can be None.
if (flags
[0],flags
[-1]) != ('(',')'):
date_time
= Time2Internaldate(date_time
)
self
.literal
= MapCRLF
.sub(CRLF
, message
)
return self
._simple
_command
(name
, mailbox
, flags
, date_time
)
def authenticate(self
, mechanism
, authobject
):
"""Authenticate command - requires response processing.
'mechanism' specifies which authentication mechanism is to
be used - it must appear in <instance>.capabilities in the
'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
# XXX: shouldn't this code be removed, not commented out?
#if not cap in self.capabilities: # Let the server decide!
# raise self.error("Server doesn't allow %s authentication." % mech)
self
.literal
= _Authenticator(authobject
).process
typ
, dat
= self
._simple
_command
('AUTHENTICATE', mech
)
raise self
.error(dat
[-1])
"""Checkpoint mailbox on server.
(typ, [data]) = <instance>.check()
return self
._simple
_command
('CHECK')
"""Close currently selected mailbox.
Deleted messages are removed from writable mailbox.
This is the recommended command before 'LOGOUT'.
(typ, [data]) = <instance>.close()
typ
, dat
= self
._simple
_command
('CLOSE')
def copy(self
, message_set
, new_mailbox
):
"""Copy 'message_set' messages onto end of 'new_mailbox'.
(typ, [data]) = <instance>.copy(message_set, new_mailbox)
return self
._simple
_command
('COPY', message_set
, new_mailbox
)
def create(self
, mailbox
):
(typ, [data]) = <instance>.create(mailbox)
return self
._simple
_command
('CREATE', mailbox
)
def delete(self
, mailbox
):
(typ, [data]) = <instance>.delete(mailbox)
return self
._simple
_command
('DELETE', mailbox
)
def deleteacl(self
, mailbox
, who
):
"""Delete the ACLs (remove any rights) set for who on mailbox.
(typ, [data]) = <instance>.deleteacl(mailbox, who)
return self
._simple
_command
('DELETEACL', mailbox
, who
)
"""Permanently remove deleted items from selected mailbox.
Generates 'EXPUNGE' response for each deleted message.
(typ, [data]) = <instance>.expunge()
'data' is list of 'EXPUNGE'd message numbers in order received.
typ
, dat
= self
._simple
_command
(name
)
return self
._untagged
_response
(typ
, dat
, name
)
def fetch(self
, message_set
, message_parts
):
"""Fetch (parts of) messages.
(typ, [data, ...]) = <instance>.fetch(message_set, message_parts)
'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.
typ
, dat
= self
._simple
_command
(name
, message_set
, message_parts
)
return self
._untagged
_response
(typ
, dat
, name
)
def getacl(self
, mailbox
):
"""Get the ACLs for a mailbox.
(typ, [data]) = <instance>.getacl(mailbox)
typ
, dat
= self
._simple
_command
('GETACL', mailbox
)
return self
._untagged
_response
(typ
, dat
, 'ACL')
def getquota(self
, root
):
"""Get the quota root's resource usage and limits.
Part of the IMAP4 QUOTA extension defined in rfc2087.
(typ, [data]) = <instance>.getquota(root)
typ
, dat
= self
._simple
_command
('GETQUOTA', root
)
return self
._untagged
_response
(typ
, dat
, 'QUOTA')
def getquotaroot(self
, mailbox
):
"""Get the list of quota roots for the named mailbox.
(typ, [[QUOTAROOT responses...], [QUOTA responses]]) = <instance>.getquotaroot(mailbox)
typ
, dat
= self
._simple
_command
('GETQUOTAROOT', mailbox
)
typ
, quota
= self
._untagged
_response
(typ
, dat
, 'QUOTA')
typ
, quotaroot
= self
._untagged
_response
(typ
, dat
, 'QUOTAROOT')
return typ
, [quotaroot
, quota
]
def list(self
, directory
='""', pattern
='*'):
"""List mailbox names in directory matching pattern.
(typ, [data]) = <instance>.list(directory='""', pattern='*')
'data' is list of LIST responses.
typ
, dat
= self
._simple
_command
(name
, directory
, pattern
)
return self
._untagged
_response
(typ
, dat
, name
)
def login(self
, user
, password
):
"""Identify client using plaintext password.
(typ, [data]) = <instance>.login(user, password)
NB: 'password' will be quoted.
typ
, dat
= self
._simple
_command
('LOGIN', user
, self
._quote
(password
))
raise self
.error(dat
[-1])
def login_cram_md5(self
, user
, password
):
""" Force use of CRAM-MD5 authentication.
(typ, [data]) = <instance>.login_cram_md5(user, password)
self
.user
, self
.password
= user
, password
return self
.authenticate('CRAM-MD5', self
._CRAM
_MD
5_AUTH
)
def _CRAM_MD5_AUTH(self
, challenge
):
""" Authobject to use with CRAM-MD5 authentication. """
return self
.user
+ " " + hmac
.HMAC(self
.password
, challenge
).hexdigest()
"""Shutdown connection to server.
(typ, [data]) = <instance>.logout()
Returns server 'BYE' response.
try: typ
, dat
= self
._simple
_command
('LOGOUT')
except: typ
, dat
= 'NO', ['%s: %s' % sys
.exc_info()[:2]]
if 'BYE' in self
.untagged_responses
:
return 'BYE', self
.untagged_responses
['BYE']
def lsub(self
, directory
='""', pattern
='*'):
"""List 'subscribed' mailbox names in directory matching pattern.
(typ, [data, ...]) = <instance>.lsub(directory='""', pattern='*')
'data' are tuples of message part envelope and data.
typ
, dat
= self
._simple
_command
(name
, directory
, pattern
)
return self
._untagged
_response
(typ
, dat
, name
)
def myrights(self
, mailbox
):
"""Show my ACLs for a mailbox (i.e. the rights that I have on mailbox).
(typ, [data]) = <instance>.myrights(mailbox)
typ
,dat
= self
._simple
_command
('MYRIGHTS', mailbox
)
return self
._untagged
_response
(typ
, dat
, 'MYRIGHTS')
""" Returns IMAP namespaces ala rfc2342
(typ, [data, ...]) = <instance>.namespace()
typ
, dat
= self
._simple
_command
(name
)
return self
._untagged
_response
(typ
, dat
, name
)
(typ, [data]) = <instance>.noop()
self
._dump
_ur
(self
.untagged_responses
)
return self
._simple
_command
('NOOP')
def partial(self
, message_num
, message_part
, start
, length
):
"""Fetch truncated part of a message.
(typ, [data, ...]) = <instance>.partial(message_num, message_part, start, length)
'data' is tuple of message part envelope and data.
typ
, dat
= self
._simple
_command
(name
, message_num
, message_part
, start
, length
)
return self
._untagged
_response
(typ
, dat
, 'FETCH')
def proxyauth(self
, user
):
"""Assume authentication as "user".
Allows an authorised administrator to proxy into any user's
(typ, [data]) = <instance>.proxyauth(user)
return self
._simple
_command
('PROXYAUTH', user
)
def rename(self
, oldmailbox
, newmailbox
):
"""Rename old mailbox name to new.
(typ, [data]) = <instance>.rename(oldmailbox, newmailbox)
return self
._simple
_command
('RENAME', oldmailbox
, newmailbox
)
def search(self
, charset
, *criteria
):
"""Search mailbox for matching messages.
(typ, [data]) = <instance>.search(charset, criterion, ...)
'data' is space separated list of matching message numbers.
typ
, dat
= self
._simple
_command
(name
, 'CHARSET', charset
, *criteria
)
typ
, dat
= self
._simple
_command
(name
, *criteria
)
return self
._untagged
_response
(typ
, dat
, name
)
def select(self
, mailbox
='INBOX', readonly
=None):
Flush all untagged responses.
(typ, [data]) = <instance>.select(mailbox='INBOX', readonly=None)
'data' is count of messages in mailbox ('EXISTS' response).
Mandated responses are ('FLAGS', 'EXISTS', 'RECENT', 'UIDVALIDITY'), so
other responses should be obtained via <instance>.response('FLAGS') etc.
self
.untagged_responses
= {} # Flush old responses.
self
.is_readonly
= readonly
typ
, dat
= self
._simple
_command
(name
, mailbox
)
self
.state
= 'AUTH' # Might have been 'SELECTED'
if 'READ-ONLY' in self
.untagged_responses \
self
._dump
_ur
(self
.untagged_responses
)
raise self
.readonly('%s is not writable' % mailbox
)
return typ
, self
.untagged_responses
.get('EXISTS', [None])
def setacl(self
, mailbox
, who
, what
):
(typ, [data]) = <instance>.setacl(mailbox, who, what)
return self
._simple
_command
('SETACL', mailbox
, who
, what
)
def setquota(self
, root
, limits
):
"""Set the quota root's resource limits.
(typ, [data]) = <instance>.setquota(root, limits)
typ
, dat
= self
._simple
_command
('SETQUOTA', root
, limits
)
return self
._untagged
_response
(typ
, dat
, 'QUOTA')
def sort(self
, sort_criteria
, charset
, *search_criteria
):
"""IMAP4rev1 extension SORT command.
(typ, [data]) = <instance>.sort(sort_criteria, charset, search_criteria, ...)
#if not name in self.capabilities: # Let the server decide!
# raise self.error('unimplemented extension command: %s' % name)
if (sort_criteria
[0],sort_criteria
[-1]) != ('(',')'):
sort_criteria
= '(%s)' % sort_criteria
typ
, dat
= self
._simple
_command
(name
, sort_criteria
, charset
, *search_criteria
)
return self
._untagged
_response
(typ
, dat
, name
)
def status(self
, mailbox
, names
):
"""Request named status conditions for mailbox.
(typ, [data]) = <instance>.status(mailbox, names)
#if self.PROTOCOL_VERSION == 'IMAP4': # Let the server decide!
# raise self.error('%s unimplemented in IMAP4 (obtain IMAP4rev1 server, or re-code)' % name)
typ
, dat
= self
._simple
_command
(name
, mailbox
, names
)
return self
._untagged
_response
(typ
, dat
, name
)
def store(self
, message_set
, command
, flags
):
"""Alters flag dispositions for messages in mailbox.
(typ, [data]) = <instance>.store(message_set, command, flags)
if (flags
[0],flags
[-1]) != ('(',')'):
flags
= '(%s)' % flags
# Avoid quoting the flags
typ
, dat
= self
._simple
_command
('STORE', message_set
, command
, flags
)
return self
._untagged
_response
(typ
, dat
, 'FETCH')
def subscribe(self
, mailbox
):
"""Subscribe to new mailbox.
(typ, [data]) = <instance>.subscribe(mailbox)
return self
._simple
_command
('SUBSCRIBE', mailbox
)
def thread(self
, threading_algorithm
, charset
, *search_criteria
):
"""IMAPrev1 extension THREAD command.
(type, [data]) = <instance>.thread(threading_alogrithm, charset, search_criteria, ...)
typ
, dat
= self
._simple
_command
(name
, threading_algorithm
, charset
, *search_criteria
)
return self
._untagged
_response
(typ
, dat
, name
)
def uid(self
, command
, *args
):
"""Execute "command arg ..." with messages identified by UID,
rather than message number.
(typ, [data]) = <instance>.uid(command, arg1, arg2, ...)
Returns response appropriate to 'command'.
command
= command
.upper()
if not command
in Commands
:
raise self
.error("Unknown IMAP4 UID command: %s" % command
)
if self
.state
not in Commands
[command
]:
raise self
.error('command %s illegal in state %s'
typ
, dat
= self
._simple
_command
(name
, command
, *args
)
if command
in ('SEARCH', 'SORT'):
return self
._untagged
_response
(typ
, dat
, name
)
def unsubscribe(self
, mailbox
):
"""Unsubscribe from old mailbox.
(typ, [data]) = <instance>.unsubscribe(mailbox)
return self
._simple
_command
('UNSUBSCRIBE', mailbox
)
def xatom(self
, name
, *args
):
"""Allow simple extension commands
notified by server in CAPABILITY response.
Assumes command is legal in current state.
(typ, [data]) = <instance>.xatom(name, arg, ...)
Returns response appropriate to extension command `name'.
#if not name in self.capabilities: # Let the server decide!
# raise self.error('unknown extension command: %s' % name)
Commands
[name
] = (self
.state
,)
return self
._simple
_command
(name
, *args
)
def _append_untagged(self
, typ
, dat
):
ur
= self
.untagged_responses
self
._mesg
('untagged_responses[%s] %s += ["%s"]' %
(typ
, len(ur
.get(typ
,'')), dat
))
bye
= self
.untagged_responses
.get('BYE')
raise self
.abort(bye
[-1])
def _command(self
, name
, *args
):
if self
.state
not in Commands
[name
]:
'command %s illegal in state %s' % (name
, self
.state
))
for typ
in ('OK', 'NO', 'BAD'):
if typ
in self
.untagged_responses
:
del self
.untagged_responses
[typ
]
if 'READ-ONLY' in self
.untagged_responses \
and not self
.is_readonly
:
raise self
.readonly('mailbox status changed to READ-ONLY')
data
= '%s %s' % (tag
, name
)
data
= '%s %s' % (data
, self
._checkquote
(arg
))
if type(literal
) is type(self
._command
):
data
= '%s {%s}' % (data
, len(literal
))
self
._mesg
('> %s' % data
)
self
.send('%s%s' % (data
, CRLF
))
except (socket
.error
, OSError), val
:
raise self
.abort('socket error: %s' % val
)
# Wait for continuation response
while self
._get
_response
():
if self
.tagged_commands
[tag
]: # BAD/NO?
literal
= literator(self
.continuation_response
)
self
._mesg
('write literal size %s' % len(literal
))
except (socket
.error
, OSError), val
:
raise self
.abort('socket error: %s' % val
)
def _command_complete(self
, name
, tag
):
typ
, data
= self
._get
_tagged
_response
(tag
)
raise self
.abort('command: %s => %s' % (name
, val
))
raise self
.error('command: %s => %s' % (name
, val
))
raise self
.error('%s command error: %s %s' % (name
, typ
, data
))
# Read response and store.
# Returns None for continuation responses,
# otherwise first response line received.
# Command completion response?
if self
._match
(self
.tagre
, resp
):
tag
= self
.mo
.group('tag')
if not tag
in self
.tagged_commands
:
raise self
.abort('unexpected tagged response: %s' % resp
)
typ
= self
.mo
.group('type')
dat
= self
.mo
.group('data')
self
.tagged_commands
[tag
] = (typ
, [dat
])
# '*' (untagged) responses?
if not self
._match
(Untagged_response
, resp
):
if self
._match
(Untagged_status
, resp
):
dat2
= self
.mo
.group('data2')
# Only other possibility is '+' (continuation) response...
if self
._match
(Continuation
, resp
):
self
.continuation_response
= self
.mo
.group('data')
return None # NB: indicates continuation
raise self
.abort("unexpected response: '%s'" % resp
)
typ
= self
.mo
.group('type')
dat
= self
.mo
.group('data')
if dat
is None: dat
= '' # Null untagged response
if dat2
: dat
= dat
+ ' ' + dat2
# Is there a literal to come?
while self
._match
(Literal
, dat
):
# Read literal direct from connection.
size
= int(self
.mo
.group('size'))
self
._mesg
('read literal size %s' % size
)
# Store response with literal as tuple
self
._append
_untagged
(typ
, (dat
, data
))
# Read trailer - possibly containing another literal
self
._append
_untagged
(typ
, dat
)
# Bracketed response information?
if typ
in ('OK', 'NO', 'BAD') and self
._match
(Response_code
, dat
):
self
._append
_untagged
(self
.mo
.group('type'), self
.mo
.group('data'))
if self
.debug
>= 1 and typ
in ('NO', 'BAD', 'BYE'):
self
._mesg
('%s response: %s' % (typ
, dat
))
def _get_tagged_response(self
, tag
):
result
= self
.tagged_commands
[tag
]
del self
.tagged_commands
[tag
]
# Some have reported "unexpected response" exceptions.
# Note that ignoring them here causes loops.
# Instead, send me details of the unexpected response and
# I'll update the code in `_get_response()'.
raise self
.abort('socket error: EOF')
# Protocol mandates all lines terminated by CRLF
self
._mesg
('< %s' % line
)
def _match(self
, cre
, s
):
# Run compiled regular expression match method on 's'.
# Save result, return success.
if self
.mo
is not None and self
.debug
>= 5:
self
._mesg
("\tmatched r'%s' => %r" % (cre
.pattern
, self
.mo
.groups()))
return self
.mo
is not None
tag
= '%s%s' % (self
.tagpre
, self
.tagnum
)
self
.tagnum
= self
.tagnum
+ 1
self
.tagged_commands
[tag
] = None
def _checkquote(self
, arg
):
# Must quote command args if non-alphanumeric chars present,
# and not already quoted.
if type(arg
) is not type(''):
if len(arg
) >= 2 and (arg
[0],arg
[-1]) in (('(',')'),('"','"')):
if arg
and self
.mustquote
.search(arg
) is None:
arg
= arg
.replace('\\', '\\\\')
arg
= arg
.replace('"', '\\"')
def _simple_command(self
, name
, *args
):
return self
._command
_complete
(name
, self
._command
(name
, *args
))
def _untagged_response(self
, typ
, dat
, name
):
if not name
in self
.untagged_responses
:
data
= self
.untagged_responses
.pop(name
)
self
._mesg
('untagged_responses[%s] => %s' % (name
, data
))
def _mesg(self
, s
, secs
=None):
tm
= time
.strftime('%M:%S', time
.localtime(secs
))
sys
.stderr
.write(' %s.%02d %s\n' % (tm
, (secs
*100)%100, s
))
def _dump_ur(self
, dict):
# Dump untagged responses (in `dict').
l
= map(lambda x
:'%s: "%s"' % (x
[0], x
[1][0] and '" "'.join(x
[1]) or ''), l
)
self
._mesg
('untagged responses dump:%s%s' % (t
, t
.join(l
)))
# Keep log of last `_cmd_log_len' interactions for debugging.
self
._cmd
_log
[self
._cmd
_log
_idx
] = (line
, time
.time())
if self
._cmd
_log
_idx
>= self
._cmd
_log
_len
:
self
._mesg
('last %d IMAP4 interactions:' % len(self
._cmd
_log
))
i
, n
= self
._cmd
_log
_idx
, self
._cmd
_log
_len
self
._mesg
(*self
._cmd
_log
[i
])
if i
>= self
._cmd
_log
_len
:
"""IMAP4 client class over SSL connection
Instantiate with: IMAP4_SSL([host[, port[, keyfile[, certfile]]]])
host - host's name (default: localhost);
port - port number (default: standard IMAP4 SSL port).
keyfile - PEM formatted file that contains your private key (default: None);
certfile - PEM formatted certificate chain file (default: None);
for more documentation see the docstring of the parent class IMAP4.
def __init__(self
, host
= '', port
= IMAP4_SSL_PORT
, keyfile
= None, certfile
= None):
IMAP4
.__init__(self
, host
, port
)
def open(self
, host
= '', port
= IMAP4_SSL_PORT
):
"""Setup connection to remote server on "host:port".
(default: localhost:standard IMAP4 SSL port).
This connection will be used by the routines:
read, readline, send, shutdown.
self
.sock
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
self
.sock
.connect((host
, port
))
self
.sslobj
= socket
.ssl(self
.sock
, self
.keyfile
, self
.certfile
)
"""Read 'size' bytes from remote."""
# sslobj.read() sometimes returns < size bytes
data
= self
.sslobj
.read(size
-read
)
"""Read line from remote."""
# NB: socket.ssl needs a "readline" method, or perhaps a "makefile" method.
char
= self
.sslobj
.read(1)
if char
== "\n": return ''.join(line
)
"""Send data to remote."""
# NB: socket.ssl needs a "sendall" method to match socket objects.
sent
= self
.sslobj
.write(data
)
"""Close I/O established in "open"."""
"""Return socket instance used to connect to IMAP4 server.
socket = <instance>.socket()
"""Return SSLObject instance used to communicate with the IMAP4 server.
ssl = <instance>.socket.ssl()
class IMAP4_stream(IMAP4
):
"""IMAP4 client class over a stream
Instantiate with: IMAP4_stream(command)
where "command" is a string that can be passed to os.popen2()
for more documentation see the docstring of the parent class IMAP4.
def __init__(self
, command
):
def open(self
, host
= None, port
= None):
"""Setup a stream connection.
This connection will be used by the routines:
read, readline, send, shutdown.
self
.host
= None # For compatibility with parent class
self
.writefile
, self
.readfile
= os
.popen2(self
.command
)
"""Read 'size' bytes from remote."""
return self
.readfile
.read(size
)
"""Read line from remote."""
return self
.readfile
.readline()
"""Send data to remote."""
self
.writefile
.write(data
)
"""Close I/O established in "open"."""
"""Private class to provide en/decoding
for base64-based authentication conversation.
def __init__(self
, mechinst
):
self
.mech
= mechinst
# Callable object to provide/process data
ret
= self
.mech(self
.decode(data
))
return '*' # Abort conversation
# Invoke binascii.b2a_base64 iteratively with
# short even length buffers, strip the trailing
# line feed from the result and append. "Even"
# means a number that factors to both 6 and 8,
# so when it gets to the end of the 8-bit input
# there's no partial 6-bit output.
e
= binascii
.b2a_base64(t
)
return binascii
.a2b_base64(inp
)
Mon2num
= {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
def Internaldate2tuple(resp
):
"""Convert IMAP4 INTERNALDATE to UT.
Returns Python time module tuple.
mo
= InternalDate
.match(resp
)
mon
= Mon2num
[mo
.group('mon')]
zonen
= mo
.group('zonen')
day
= int(mo
.group('day'))
year
= int(mo
.group('year'))
hour
= int(mo
.group('hour'))
min = int(mo
.group('min'))
sec
= int(mo
.group('sec'))
zoneh
= int(mo
.group('zoneh'))
zonem
= int(mo
.group('zonem'))
# INTERNALDATE timezone must be subtracted to get UT
zone
= (zoneh
*60 + zonem
)*60
tt
= (year
, mon
, day
, hour
, min, sec
, -1, -1, -1)
# Following is necessary because the time module has no 'mkgmtime'.
# 'mktime' assumes arg in local timezone, so adds timezone/altzone.
if time
.daylight
and lt
[-1]:
zone
= zone
+ time
.altzone
zone
= zone
+ time
.timezone
return time
.localtime(utc
- zone
)
"""Convert integer to A-P string representation."""
val
= ''; AP
= 'ABCDEFGHIJKLMNOP'
num
, mod
= divmod(num
, 16)
"""Convert IMAP4 flags response to python tuple."""
return tuple(mo
.group('flags').split())
def Time2Internaldate(date_time
):
"""Convert 'date_time' to IMAP4 INTERNALDATE representation.
Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"'
if isinstance(date_time
, (int, float)):
tt
= time
.localtime(date_time
)
elif isinstance(date_time
, (tuple, time
.struct_time
)):
elif isinstance(date_time
, str) and (date_time
[0],date_time
[-1]) == ('"','"'):
return date_time
# Assume in correct format
raise ValueError("date_time not of a known type")
dt
= time
.strftime("%d-%b-%Y %H:%M:%S", tt
)
if time
.daylight
and tt
[-1]:
return '"' + dt
+ " %+03d%02d" % divmod(zone
//60, 60) + '"'
if __name__
== '__main__':
# To test: invoke either as 'python imaplib.py [IMAP4_server_hostname]'
# or 'python imaplib.py -s "rsh IMAP4_server_hostname exec /etc/rimapd"'
# to test the IMAP4_stream class
optlist
, args
= getopt
.getopt(sys
.argv
[1:], 'd:s:')
except getopt
.error
, val
:
if not args
: args
= (stream_command
,)
if not args
: args
= ('',)
PASSWD
= getpass
.getpass("IMAP password for %s on %s: " % (USER
, host
or "localhost"))
test_mesg
= 'From: %(user)s@localhost%(lf)sSubject: IMAP4 test%(lf)s%(lf)sdata...%(lf)s' % {'user':USER
, 'lf':'\n'}
('login', (USER
, PASSWD
)),
('create', ('/tmp/xxx 1',)),
('rename', ('/tmp/xxx 1', '/tmp/yyy')),
('CREATE', ('/tmp/yyz 2',)),
('append', ('/tmp/yyz 2', None, None, test_mesg
)),
('list', ('/tmp', 'yy*')),
('select', ('/tmp/yyz 2',)),
('search', (None, 'SUBJECT', 'test')),
('fetch', ('1', '(FLAGS INTERNALDATE RFC822)')),
('store', ('1', 'FLAGS', '(\Deleted)')),
('response',('UIDVALIDITY',)),
('uid', ('SEARCH', 'ALL')),
('response', ('EXISTS',)),
('append', (None, None, None, test_mesg
)),
M
._mesg
('%s %s' % (cmd
, args
))
typ
, dat
= getattr(M
, cmd
)(*args
)
M
._mesg
('%s => %s %s' % (cmd
, typ
, dat
))
if typ
== 'NO': raise dat
[0]
M
= IMAP4_stream(stream_command
)
test_seq1
= test_seq1
[1:] # Login not needed
M
._mesg
('PROTOCOL_VERSION = %s' % M
.PROTOCOL_VERSION
)
M
._mesg
('CAPABILITIES = %r' % (M
.capabilities
,))
for cmd
,args
in test_seq1
:
for ml
in run('list', ('/tmp/', 'yy%')):
mo
= re
.match(r
'.*"([^"]+)"$', ml
)
if mo
: path
= mo
.group(1)
else: path
= ml
.split()[-1]
for cmd
,args
in test_seq2
:
if (cmd
,args
) != ('uid', ('SEARCH', 'ALL')):
run('uid', ('FETCH', '%s' % uid
[-1],
'(FLAGS INTERNALDATE RFC822.SIZE RFC822.HEADER RFC822.TEXT)'))
If you would like to see debugging output,