imaplib.py

来自「mallet是自然语言处理、机器学习领域的一个开源项目。」· Python 代码 · 共 1,209 行 · 第 1/3 页

PY
1,209
字号
"""IMAP4 client.Based on RFC 2060.Public class:           IMAP4Public variable:        DebugPublic functions:       Internaldate2tuple                        Int2AP                        ParseFlags                        Time2Internaldate"""# 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.__version__ = "2.49"import binascii, re, socket, time, random, sys__all__ = ["IMAP4", "Internaldate2tuple",           "Int2AP", "ParseFlags", "Time2Internaldate"]#       GlobalsCRLF = '\r\n'Debug = 0IMAP4_PORT = 143AllowedVersions = ('IMAP4REV1', 'IMAP4')        # Most recent first#       CommandsCommands = {        # name            valid states        'APPEND':       ('AUTH', 'SELECTED'),        'AUTHENTICATE': ('NONAUTH',),        'CAPABILITY':   ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),        'CHECK':        ('SELECTED',),        'CLOSE':        ('SELECTED',),        'COPY':         ('SELECTED',),        'CREATE':       ('AUTH', 'SELECTED'),        'DELETE':       ('AUTH', 'SELECTED'),        'EXAMINE':      ('AUTH', 'SELECTED'),        'EXPUNGE':      ('SELECTED',),        'FETCH':        ('SELECTED',),        'GETACL':       ('AUTH', 'SELECTED'),        'LIST':         ('AUTH', 'SELECTED'),        'LOGIN':        ('NONAUTH',),        'LOGOUT':       ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),        'LSUB':         ('AUTH', 'SELECTED'),        'NAMESPACE':    ('AUTH', 'SELECTED'),        'NOOP':         ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),        'PARTIAL':      ('SELECTED',),        'RENAME':       ('AUTH', 'SELECTED'),        'SEARCH':       ('SELECTED',),        'SELECT':       ('AUTH', 'SELECTED'),        'SETACL':       ('AUTH', 'SELECTED'),        'SORT':         ('SELECTED',),        'STATUS':       ('AUTH', 'SELECTED'),        'STORE':        ('SELECTED',),        'SUBSCRIBE':    ('AUTH', 'SELECTED'),        'UID':          ('SELECTED',),        'UNSUBSCRIBE':  ('AUTH', 'SELECTED'),        }#       Patterns to match server responsesContinuation = 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])'        r'"')Literal = re.compile(r'.*{(?P<size>\d+)}$')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>.*))?')class IMAP4:    """IMAP4 client class.    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    name (in 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 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.    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.    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.    """    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.host = host        self.port = port        self.debug = Debug        self.state = 'LOGOUT'        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        self.tagnum = 0        # Open socket to server.        self.open(host, port)        # 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>'                        + self.tagpre                        + r'\d+) (?P<type>[A-Z]+) (?P<data>.*)')        # Get server welcome message,        # request and store CAPABILITY response.        if __debug__:            if self.debug >= 1:                _mesg('imaplib version %s' % __version__)                _mesg('new IMAP4 connection, tag=%s' % self.tagpre)        self.welcome = self._get_response()        if self.untagged_responses.has_key('PREAUTH'):            self.state = 'AUTH'        elif self.untagged_responses.has_key('OK'):            self.state = 'NONAUTH'        else:            raise self.error(self.welcome)        cap = 'CAPABILITY'        self._simple_command(cap)        if not self.untagged_responses.has_key(cap):            raise self.error('no CAPABILITY response from server')        self.capabilities = tuple(self.untagged_responses[cap][-1].upper().split())        if __debug__:            if self.debug >= 3:                _mesg('CAPABILITIES: %s' % `self.capabilities`)        for version in AllowedVersions:            if not version in self.capabilities:                continue            self.PROTOCOL_VERSION = version            return        raise self.error('server not IMAP4 compliant')    def __getattr__(self, attr):        #       Allow UPPERCASE variants of IMAP4 command methods.        if Commands.has_key(attr):            return getattr(self, attr.lower())        raise AttributeError("Unknown IMAP4 command: '%s'" % attr)    #       Overridable methods    def open(self, host, port):        """Setup connection to remote server on "host: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((self.host, self.port))        self.file = self.sock.makefile('rb')    def read(self, size):        """Read 'size' bytes from remote."""        return self.file.read(size)    def readline(self):        """Read line from remote."""        return self.file.readline()    def send(self, data):        """Send data to remote."""        self.sock.sendall(data)    def shutdown(self):        """Close I/O established in "open"."""        self.file.close()        self.sock.close()    def socket(self):        """Return socket instance used to connect to IMAP4 server.        socket = <instance>.socket()        """        return self.sock    #       Utility methods    def recent(self):        """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.        """        name = 'RECENT'        typ, dat = self._untagged_response('OK', [None], name)        if dat[-1]:            return typ, dat        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())    #       IMAP4 commands    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.        """        name = 'APPEND'        if not mailbox:            mailbox = 'INBOX'        if flags:            if (flags[0],flags[-1]) != ('(',')'):                flags = '(%s)' % flags        else:            flags = None        if date_time:            date_time = Time2Internaldate(date_time)        else:            date_time = None        self.literal = 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        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.        """        mech = mechanism.upper()        cap = 'AUTH=%s' % mech        if not cap in self.capabilities:            raise self.error("Server doesn't allow %s authentication." % mech)        self.literal = _Authenticator(authobject).process        typ, dat = self._simple_command('AUTHENTICATE', mech)        if typ != 'OK':            raise self.error(dat[-1])        self.state = 'AUTH'        return typ, dat    def check(self):        """Checkpoint mailbox on server.        (typ, [data]) = <instance>.check()        """        return self._simple_command('CHECK')    def close(self):        """Close currently selected mailbox.        Deleted messages are removed from writable mailbox.        This is the recommended command before 'LOGOUT'.        (typ, [data]) = <instance>.close()        """        try:            typ, dat = self._simple_command('CLOSE')        finally:            self.state = 'AUTH'        return typ, dat    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):        """Create new mailbox.        (typ, [data]) = <instance>.create(mailbox)        """        return self._simple_command('CREATE', mailbox)    def delete(self, mailbox):        """Delete old mailbox.        (typ, [data]) = <instance>.delete(mailbox)        """        return self._simple_command('DELETE', mailbox)    def expunge(self):        """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.        """        name = 'EXPUNGE'        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.        """        name = 'FETCH'        typ, dat = self._simple_command(name, message_set, message_parts)        return self._untagged_response(typ, dat, name)    def getacl(self, mailbox):

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?