imaplib — IMAP4 协议客户端

源代码: Lib/imaplib.py


此模块定义 3 个类, IMAP4 , IMAP4_SSL and IMAP4_stream ,封装到 IMAP4 服务器的连接和实现 IMAP4rev1 客户端协议的大子集作为定义在 RFC 2060 。它向后兼容 IMAP4 ( RFC 1730 ) 服务器,但注意 STATUS 命令在 IMAP4 中不支持。

3 个类的提供通过 imaplib 模块, IMAP4 是基类:

class imaplib. IMAP4 ( host='' , port=IMAP4_PORT , timeout=None )

此类实现实际 IMAP4 协议。创建连接并确定协议版本 (IMAP4 或 IMAP4rev1) 当初始化实例时。若 host 未指定, '' (本地主机) 被使用。若 port 被省略,标准 IMAP4 端口 (143) 被使用。可选 timeout 参数指定试图连接的超时 (以秒为单位)。若超时不给定或为 None,将使用全局默认套接字超时。

IMAP4 类支持 with 语句。当像这样使用时,IMAP4 LOGOUT 命令被自动发出当 with 语句退出。如:

>>> from imaplib import IMAP4
>>> with IMAP4("domain.org") as M:
...     M.noop()
...
('OK', [b'Nothing Accomplished. d25if65hy903weo.87'])
									

3.5 版改变: 支持 with 语句被添加。

3.9 版改变: 可选 timeout 参数被添加。

3 个异常被定义作为属性对于 IMAP4 类:

exception IMAP4. error

由任何错误引发的异常。异常原因以字符串形式被传递给构造函数。

exception IMAP4. abort

IMAP4 服务器错误导致此异常被引发。这是子类化的 IMAP4.error 。注意,关闭实例并实例化新的实例通常允许从此异常恢复。

exception IMAP4. readonly

此异常被引发当通过服务器改变可写邮箱的状态时。这是子类化的 IMAP4.error 。某些其它客户端现在拥有写权限,但需要重新打开邮箱以重新获得写权限。

还有用于安全连接的子类:

class imaplib. IMAP4_SSL ( host='' , port=IMAP4_SSL_PORT , keyfile=None , certfile=None , ssl_context=None , timeout=None )

这是子类派生自 IMAP4 通过 SSL (安全套接字层) 加密套接字连接 (要使用此类需要采用 SSL 支持编译的套接字模块)。若 host 未指定, '' (本地主机) 被使用。若 port 被省略,使用标准 IMAP4-over-SSL 端口 993。 ssl_context ssl.SSLContext 对象允许捆绑 SSL 配置选项、证书及私钥成单一 (潜在长期存活) 结构。请阅读 安全注意事项 了解最佳实践。

keyfile and certfile 是传统替代对于 ssl_context - they can point to PEM-formatted private key and certificate chain files for the SSL connection. Note that the keyfile / certfile parameters are mutually exclusive with ssl_context ValueError 被引发若 keyfile / certfile is provided along with ssl_context .

可选 timeout 参数指定试图连接的超时 (以秒为单位)。若超时不给定或为 None,将使用全局默认套接字超时。

3.3 版改变: ssl_context 参数被添加。

3.4 版改变: 类现在支持主机名校验采用 ssl.SSLContext.check_hostname and SNI (服务器名称指示) (见 ssl.HAS_SNI ).

从 3.6 版起弃用: keyfile and certfile 弃用代之 ssl_context 。请使用 ssl.SSLContext.load_cert_chain() 代替,或让 ssl.create_default_context() 为您选择系统的受信任 CA 证书。

3.9 版改变: 可选 timeout 参数被添加。

第 2 个子类允许通过子级进程创建连接:

class imaplib. IMAP4_stream ( command )

这是子类派生自 IMAP4 连接到 stdin/stdout 文件描述符创建通过传递 command to subprocess.Popen() .

定义以下实用函数:

imaplib. Internaldate2tuple ( datestr )

剖析 IMAP4 INTERNALDATE 字符串并返回相应当地时间。返回值为 time.struct_time 元组或 None 如果字符串格式错误。

imaplib. Int2AP ( num )

将整数转换成字节表示使用字符来自集 [ A .. P ].

imaplib. ParseFlags ( flagstr )

转换 IMAP4 FLAGS 响应成单个标志的元组。

imaplib. Time2Internaldate ( date_time )

转换 date_time 到 IMAP4 INTERNALDATE 表示。返回值是以下形式字符串: "DD-Mmm-YYYY HH:MM:SS +HHMM" (包括双引号)。 date_time argument can be a number (int or float) representing seconds since epoch (as returned by time.time() ), a 9-tuple representing local time an instance of time.struct_time (as returned by time.localtime() ), an aware instance of datetime.datetime , or a double-quoted string. In the last case, it is assumed to already be in the correct format.

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.

另请参阅

Documents describing the protocol, sources for servers implementing it, by the University of Washington’s IMAP Information Center can all be found at ( 源代码 ) https://github.com/uw-imap/imap ( 无维护 ).

IMAP4 对象

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 自变量到 LOGIN command is always quoted. If you want to avoid having an argument string quoted (eg: the flags 自变量为 STORE ) then enclose the string in parentheses (eg: r'(\Deleted)' ).

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

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 实例具有下列方法:

IMAP4. append ( mailbox , flags , date_time , message )

追加 message 到命名邮箱。

IMAP4. authenticate ( mechanism , authobject )

验证命令 - 要求响应处理。

mechanism specifies which authentication mechanism is to be used - it should appear in the instance variable capabilities in the form AUTH=mechanism .

authobject 必须是可调用对象:

data = authobject(response)
										

It will be called to process server continuation responses; the response argument it is passed will be bytes . It should return bytes data that will be base64 encoded and sent to the server. It should return None if the client abort response * should be sent instead.

3.5 版改变: 字符串用户名和口令现在被编码成 utf-8 而不是局限于 ASCII。

IMAP4. check ( )

在服务器中的校验点邮箱。

IMAP4. close ( )

Close currently selected mailbox. Deleted messages are removed from writable mailbox. This is the recommended command before LOGOUT .

IMAP4. copy ( message_set , new_mailbox )

拷贝 message_set messages onto end of new_mailbox .

IMAP4. create ( mailbox )

创建新的邮箱命名 mailbox .

IMAP4. delete ( mailbox )

删除旧的邮箱命名 mailbox .

IMAP4. deleteacl ( mailbox , who )

Delete the ACLs (remove any rights) set for who on mailbox.

IMAP4. enable ( capability )

启用 capability (见 RFC 5161 ). Most capabilities do not need to be enabled. Currently only the UTF8=ACCEPT capability is supported (see RFC 6855 ).

3.5 版新增: enable() 方法自身,和 RFC 6855 支持。

IMAP4. expunge ( )

Permanently remove deleted items from selected mailbox. Generates an EXPUNGE response for each deleted message. Returned data contains a list of EXPUNGE message numbers in order received.

IMAP4. fetch ( message_set , message_parts )

Fetch (parts of) messages. message_parts should be a string of message part names enclosed within parentheses, eg: "(UID BODY[TEXT])" . Returned data are tuples of message part envelope and data.

IMAP4. getacl ( mailbox )

获取 ACL s for mailbox . The method is non-standard, but is supported by the Cyrus 服务器。

IMAP4. getannotation ( mailbox , entry , attribute )

Retrieve the specified ANNOTATION s for mailbox . The method is non-standard, but is supported by the Cyrus 服务器。

IMAP4. getquota ( root )

获取 quota root ’s resource usage and limits. This method is part of the IMAP4 QUOTA extension defined in rfc2087.

IMAP4. getquotaroot ( mailbox )

Get the list of quota roots for the named mailbox . This method is part of the IMAP4 QUOTA extension defined in rfc2087.

IMAP4. list ( [ directory [ , pattern ] ] )

List mailbox names in directory matching pattern . directory defaults to the top-level mail folder, and pattern defaults to match anything. Returned data contains a list of LIST responses.

IMAP4. login ( user , password )

Identify the client using a plaintext password. The password will be quoted.

IMAP4. login_cram_md5 ( user , password )

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 .

IMAP4. logout ( )

关闭到服务器的连接。返回服务器 BYE 响应。

3.8 版改变: The method no longer ignores silently arbitrary exceptions.

IMAP4. lsub ( directory='""' , pattern='*' )

List subscribed mailbox names in directory matching pattern. directory defaults to the top level directory and pattern defaults to match any mailbox. Returned data are tuples of message part envelope and data.

IMAP4. myrights ( mailbox )

Show my ACLs for a mailbox (i.e. the rights that I have on mailbox).

IMAP4. namespace ( )

返回 IMAP 名称空间作为定义在 RFC 2342 .

IMAP4. noop ( )

发送 NOOP 到服务器。

IMAP4. open ( host , port , timeout=None )

Opens socket to port at host 。可选 timeout parameter specifies a timeout in seconds for the connection attempt. If timeout is not given or is None, the global default socket timeout is used. Also note that if the timeout 参数被设为 0,它将引发 ValueError to reject creating a non-blocking socket. This method is implicitly called by the IMAP4 constructor. The connection objects established by this method will be used in the IMAP4.read() , IMAP4.readline() , IMAP4.send() ,和 IMAP4.shutdown() methods. You may override this method.

引发 审计事件 imaplib.open 采用自变量 self , host , port .

3.9 版改变: timeout 参数被添加。

IMAP4. partial ( message_num , message_part , start , length )

Fetch truncated part of a message. Returned data is a tuple of message part envelope and data.

IMAP4. proxyauth ( user )

Assume authentication as user . Allows an authorised administrator to proxy into any user’s mailbox.

IMAP4. read ( size )

Reads size bytes from the remote server. You may override this method.

IMAP4. readline ( )

Reads one line from the remote server. You may override this method.

IMAP4. recent ( )

Prompt server for an update. Returned data is None if no new messages, else value of RECENT 响应。

IMAP4. rename ( oldmailbox , newmailbox )

重命名邮箱命名 oldmailbox to newmailbox .

IMAP4. response ( code )

Return data for response code if received, or None . Returns the given code, instead of the usual type.

IMAP4. search ( charset , criterion [ , ... ] )

Search mailbox for matching messages. charset 可以是 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. charset 必须是 None UTF8=ACCEPT capability was enabled using the enable() 命令。

范例:

# M is a connected IMAP4 instance...
typ, msgnums = M.search(None, 'FROM', '"LDJ"')
# or:
typ, msgnums = M.search(None, '(FROM "LDJ")')
										
IMAP4. select ( mailbox='INBOX' , readonly=False )

选择邮箱。返回数据是消息计数在 mailbox ( EXISTS 响应)。默认 mailbox is 'INBOX' 。若 readonly 标志有设置,不允许修改邮箱。

IMAP4. send ( data )

发送 data 到远程服务器。可以覆盖此方法。

引发 审计事件 imaplib.send 采用自变量 self , data .

IMAP4. setacl ( mailbox , who , what )

设置 ACL for mailbox . The method is non-standard, but is supported by the Cyrus 服务器。

IMAP4. setannotation ( mailbox , entry , attribute [ , ... ] )

Set ANNOTATION s for mailbox . The method is non-standard, but is supported by the Cyrus 服务器。

IMAP4. setquota ( root , limits )

设置 quota root ’s resource limits . This method is part of the IMAP4 QUOTA extension defined in rfc2087.

IMAP4. shutdown ( )

Close connection established in open . This method is implicitly called by IMAP4.logout() . You may override this method.

IMAP4. socket ( )

返回用于连接到服务器的套接字实例。

IMAP4. sort ( sort_criteria , charset , search_criterion [ , ... ] )

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 ,和搜索 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 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.

这是 IMAP4rev1 扩展命令。

IMAP4. starttls ( ssl_context=None )

发送 STARTTLS 命令。 ssl_context argument is optional and should be a ssl.SSLContext object. This will enable encryption on the IMAP connection. Please read 安全注意事项 了解最佳实践。

3.2 版新增。

3.4 版改变: 方法现在支持主机名校验采用 ssl.SSLContext.check_hostname and SNI (服务器名称指示) (见 ssl.HAS_SNI ).

IMAP4. status ( mailbox , 名称 )

请求命名状态条件对于 mailbox .

IMAP4. store ( message_set , command , flag_list )

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”.

例如,要在所有消息上设置删除标志:

typ, data = M.search(None, 'ALL')
for num in data[0].split():
   M.store(num, '+FLAGS', '\\Deleted')
M.expunge()
										

注意

Creating flags containing ‘]’ (for example: “[test]”) violates RFC 3501 (the IMAP protocol). However, imaplib has historically allowed creation of such tags, and popular IMAP servers, such as Gmail, accept and produce such flags. There are non-Python programs which also create such tags. Although it is an RFC violation and IMAP clients and servers are supposed to be strict, imaplib nonetheless continues to allow such tags to be created for backward compatibility reasons, and as of Python 3.6, handles them if they are sent from the server, since this improves real-world compatibility.

IMAP4. subscribe ( mailbox )

订阅新邮箱。

IMAP4. thread ( threading_algorithm , charset , search_criterion [ , ... ] )

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 ,和搜索 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 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.

这是 IMAP4rev1 扩展命令。

IMAP4. uid ( command , arg [ , ... ] )

Execute command args with messages identified by UID, rather than message number. Returns response appropriate to command. At least one argument must be supplied; if none are provided, the server will return an error and an exception will be raised.

IMAP4. unsubscribe ( mailbox )

取消订阅从旧邮箱。

IMAP4. unselect ( )

imaplib.IMAP4.unselect() frees server’s resources associated with the selected mailbox and returns the server to the authenticated state. This command performs the same actions as imaplib.IMAP4.close() , except that no messages are permanently removed from the currently selected mailbox.

3.9 版新增。

IMAP4. xatom ( name [ , ... ] )

Allow simple extension commands notified by server in CAPABILITY 响应。

The following attributes are defined on instances of IMAP4 :

IMAP4. PROTOCOL_VERSION

最近支持的协议在 CAPABILITY 响应来自服务器。

IMAP4. debug

Integer value to control debugging output. The initialize value is taken from the module variable Debug . Values greater than three trace each command.

IMAP4. utf8_enabled

布尔值通常为 False ,但被设为 True enable() 命令被成功发出对于 UTF8=ACCEPT 能力。

3.5 版新增。

IMAP4 范例

这里是 (不带错误校验) 打开邮箱、检索和打印所有消息的最小范例:

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()