imaplibIMAP4 protocol clientIMAP4协议客户端

Source code: Lib/imaplib.py


This module defines three classes, IMAP4, IMAP4_SSL and IMAP4_stream, which encapsulate a connection to an IMAP4 server and implement a large subset of the IMAP4rev1 client protocol as defined in RFC 2060. 此模块定义了三个类:IMAP4IMAP4_SSLIMAP4_stream,它们封装了与IMAP4服务器的连接,并实现了RFC 2060中定义的IMAP4rev1客户端协议的一大部分。It is backward compatible with IMAP4 (RFC 1730) servers, but note that the STATUS command is not supported in IMAP4.它与IMAP4(RFC 1730)服务器向后兼容,但请注意,IMAP4不支持STATUS命令。

Three classes are provided by the imaplib module, IMAP4 is the base class:imaplib模块提供三个类,IMAP4是基类:

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

This class implements the actual IMAP4 protocol. 此类实现实际的IMAP4协议。The connection is created and protocol version (IMAP4 or IMAP4rev1) is determined when the instance is initialized. 初始化实例时,将创建连接并确定协议版本(IMAP4或IMAP4rev1)。If host is not specified, '' (the local host) is used. 如果未指定host,则使用''(本地主机)。If port is omitted, the standard IMAP4 port (143) is used. 如果省略port,则使用标准IMAP4端口(143)。The optional timeout parameter specifies a timeout in seconds for the connection attempt. 可选的timeout参数指定连接尝试的超时时间(以秒为单位)。If timeout is not given or is None, the global default socket timeout is used.如果未给定超时或为None,则使用全局默认套接字超时。

The IMAP4 class supports the with statement. When used like this, the IMAP4 LOGOUT command is issued automatically when the with statement exits. E.g.:IMAP4类支持with语句。这样使用时,当with语句退出时,IMAP4 LOGOUT命令会自动发出。如。:

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

Changed in version 3.5:版本3.5中更改: Support for the with statement was added.添加了对with语句的支持。

Changed in version 3.9:版本3.9中更改: The optional timeout parameter was added.添加了可选的timeout参数。

Three exceptions are defined as attributes of the IMAP4 class:IMAP4类的属性定义了三个例外:

exceptionIMAP4.error

Exception raised on any errors. 出现任何错误时出现异常。The reason for the exception is passed to the constructor as a string.异常的原因以字符串的形式传递给构造函数。

exceptionIMAP4.abort

IMAP4 server errors cause this exception to be raised. IMAP4服务器错误导致引发此异常。This is a sub-class of IMAP4.error. 这是IMAP4.error的子类。Note that closing the instance and instantiating a new one will usually allow recovery from this exception.请注意,关闭实例并实例化新实例通常会允许从此异常中恢复。

exceptionIMAP4.readonly

This exception is raised when a writable mailbox has its status changed by the server. 当服务器更改可写邮箱的状态时,会引发此异常。This is a sub-class of IMAP4.error. 这是IMAP4.error的子类。Some other client now has write permission, and the mailbox will need to be re-opened to re-obtain write permission.其他一些客户端现在具有写入权限,需要重新打开邮箱才能重新获得写入权限。

There’s also a subclass for secure connections:还有一个子类用于安全连接:

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

This is a subclass derived from IMAP4 that connects over an SSL encrypted socket (to use this class you need a socket module that was compiled with SSL support). 这是一个派生自IMAP4的子类,通过SSL加密的套接字进行连接(要使用此类,您需要使用SSL支持编译的套接字模块)。If host is not specified, '' (the local host) is used. 如果未指定host,则使用''(本地主机)。If port is omitted, the standard IMAP4-over-SSL port (993) is used. 如果省略port,则使用标准的IMAP4 over SSL端口(993)。ssl_context is a ssl.SSLContext object which allows bundling SSL configuration options, certificates and private keys into a single (potentially long-lived) structure. 是一个ssl.SSLContext对象,它允许将SSL配置选项、证书和私钥绑定到一个(可能是长寿命的)结构中。Please read Security considerations for best practices.请阅读最佳做法的安全注意事项

keyfile and certfile are a legacy alternative to ssl_context - they can point to PEM-formatted private key and certificate chain files for the SSL connection. keyfilecertfilessl_context的遗留替代方案,它们可以指向ssl连接的PEM格式的私钥和证书链文件。Note that the keyfile/certfile parameters are mutually exclusive with ssl_context, a ValueError is raised if keyfile/certfile is provided along with ssl_context.请注意,keyfile/certfile参数与ssl_context互斥,如果keyfile/cert文件与ssl_cntext一起提供,则会引发ValueError

The optional timeout parameter specifies a timeout in seconds for the connection attempt. 可选的timeout参数指定连接尝试的超时时间(以秒为单位)。If timeout is not given or is None, the global default socket timeout is used.如果未给定超时或为None,则使用全局默认套接字超时。

Changed in version 3.3:版本3.3中更改: ssl_context parameter was added.已添加ssl_context参数。

Changed in version 3.4:版本3.4中更改: The class now supports hostname check with ssl.SSLContext.check_hostname and Server Name Indication (see ssl.HAS_SNI).该类现在支持使用ssl.SSLContext.check_hostnameServer Name Indication进行主机名检查(请参阅ssl.HAS_SNI)。

Deprecated since version 3.6: 自3.6版以来已弃用:keyfile and certfile are deprecated in favor of ssl_context. 不赞成使用keyfilecertfile,而赞成使用ssl_contextPlease use ssl.SSLContext.load_cert_chain() instead, or let ssl.create_default_context() select the system’s trusted CA certificates for you.请改用ssl.SSLContext.load_cert_chain(),或者让ssl.create_default_context()为您选择系统的受信任CA证书。

Changed in version 3.9:版本3.9中更改: The optional timeout parameter was added.添加了可选的timeout参数。

The second subclass allows for connections created by a child process:第二个子类允许子进程创建连接:

classimaplib.IMAP4_stream(command)

This is a subclass derived from IMAP4 that connects to the stdin/stdout file descriptors created by passing command to subprocess.Popen().这是从IMAP4派生的子类,它连接到通过将命令传递给subprocess.Popen()创建的stdin/stdout文件描述符。

The following utility functions are defined:定义了以下实用程序函数:

imaplib.Internaldate2tuple(datestr)

Parse an IMAP4 INTERNALDATE string and return corresponding local time. 分析IMAP4 INTERNALDATE字符串并返回相应的本地时间。The return value is a time.struct_time tuple or None if the string has wrong format.如果字符串格式错误,则返回值为time.struct_time元组或None

imaplib.Int2AP(num)

Converts an integer into a bytes representation using characters from the set [A .. P].使用集合[A .. P]中的字符将整数转换为字节表示形式。

imaplib.ParseFlags(flagstr)

Converts an IMAP4 FLAGS response to a tuple of individual flags.将IMAP4 FLAGS响应转换为单个标志的元组。

imaplib.Time2Internaldate(date_time)

Convert date_time to an IMAP4 INTERNALDATE representation. date_time转换为IMAP4 INTERNADATE表示形式。The return value is a string in the form: "DD-Mmm-YYYY HH:MM:SS +HHMM" (including double-quotes). 返回值是一个字符串,格式为:"DD-Mmm-YYYY HH:MM:SS +HHMM"(包括双引号)。The 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. date_time参数可以是表示自epoch以来的秒数的数字(int或float)(由time.time()返回)、表示本地时间的9元组、time.struct_time的实例(由time.localtime())、datetimedatetime的感知实例或双引号字符串。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. 请注意,IMAP4消息编号会随着邮箱的变化而变化;特别是,在EXPUNGE命令执行删除操作后,其余消息将重新编号。So it is highly advisable to use UIDs instead, with the UID command.因此,强烈建议使用UID代替UID命令。

At the end of the module, there is a test section that contains a more extensive example of usage.在模块的末尾,有一个测试部分,其中包含更广泛的用法示例。

See also

Documents describing the protocol, sources for servers implementing it, by the University of Washington’s IMAP Information Center can all be found at (Source Code) https://github.com/uw-imap/imap (Not Maintained).华盛顿大学IMAP信息中心提供的描述该协议的文档以及实现该协议的服务器的来源都可以在(源代码)上找到https://github.com/uw-imap/imap未维护)。

IMAP4 Objects对象

All IMAP4rev1 commands are represented by methods of the same name, either upper-case or lower-case.所有IMAP4rev1命令都由同名的方法(大写或小写)表示。

All arguments to commands are converted to strings, except for AUTHENTICATE, and the last argument to APPEND which is passed as an IMAP4 literal. 命令的所有参数都转换为字符串,AUTHENTICATE除外,APPEND的最后一个参数作为IMAP4文本传递。If necessary (the string contains IMAP4 protocol-sensitive characters and isn’t enclosed with either parentheses or double quotes) each string is quoted. 如有必要(该字符串包含IMAP4协议敏感字符,并且没有用括号或双引号括起来),每个字符串都会被引用。However, the password argument to the LOGIN command is always quoted. 但是,LOGIN命令的password参数总是带引号的。If you want to avoid having an argument string quoted (eg: the flags argument to STORE) then enclose the string in parentheses (eg: r'(\Deleted)').如果要避免参数字符串被引用(例如:STOREflags参数),请将字符串括在括号中(例如:r'(\Deleted)')。

Each command returns a tuple: (type, [data, ...]) where type is usually 'OK' or 'NO', and data is either the text from the command response, or mandated results from the command. 每个命令都返回一个元组:(type, [data, ...]),其中type通常为'OK''NO'data要么是命令响应中的文本,要么是命令的强制结果。Each data is either a bytes, or a tuple. 每个data要么是bytes,要么是元组。If a tuple, then the first part is the header of the response, and the second part contains the data (ie: ‘literal’ value).如果是元组,则第一部分是响应的标头,第二部分包含数据(即:“literal”值)。

The message_set options to commands below is a string specifying one or more messages to be acted upon. 下面命令的message_set选项是一个字符串,指定一条或多条要操作的消息。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'). 它可以是一个简单的消息编号('1')、一个消息编号范围('2:4')或一组用逗号分隔的不连续范围('1:3,6:9')。A range can contain an asterisk to indicate an infinite upper bound ('3:*').一个范围可以包含一个星号来表示一个无限的上限('3:*')。

An IMAP4 instance has the following methods:IMAP4实例具有以下方法:

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

Append message to named mailbox.message附加到指定邮箱。

IMAP4.authenticate(mechanism, authobject)

Authenticate command — requires response processing.授权命令-需要响应处理。

mechanism specifies which authentication mechanism is to be used - it should appear in the instance variable capabilities in the form AUTH=mechanism.指定要使用的身份验证机制-它应该以AUTH=mechanism的形式出现在实例变量capabilities中。

authobject must be a callable object:必须是可调用对象:

data = authobject(response)

It will be called to process server continuation responses; the response argument it is passed will be bytes. 它将被调用来处理服务器继续响应;它传递的response参数将是bytesIt should return bytes data that will be base64 encoded and sent to the server. 它应该返回bytes数据,这些数据将以base64编码并发送到服务器。It should return None if the client abort response * should be sent instead.如果改为发送客户端中止响应*,则应返回None。

Changed in version 3.5:版本3.5中更改: string usernames and passwords are now encoded to utf-8 instead of being limited to ASCII.字符串用户名和密码现在被编码为utf-8,而不是局限于ASCII。

IMAP4.check()

Checkpoint mailbox on server.服务器上的检查点邮箱。

IMAP4.close()

Close currently selected mailbox. 关闭当前选定的邮箱。Deleted messages are removed from writable mailbox. 删除的邮件将从可写邮箱中删除。This is the recommended command before LOGOUT.这是建议在LOGOUT之前执行的命令。

IMAP4.copy(message_set, new_mailbox)

Copy message_set messages onto end of new_mailbox.message_set消息复制到new_mailbox的末尾。

IMAP4.create(mailbox)

Create new mailbox named mailbox.创建名为mailbox的新邮箱。

IMAP4.delete(mailbox)

Delete old mailbox named mailbox.删除名为mailbox的旧邮箱。

IMAP4.deleteacl(mailbox, who)

Delete the ACLs (remove any rights) set for who on mailbox.删除为邮箱上的联系人设置的ACL(删除所有权限)。

IMAP4.enable(capability)

Enable capability (see RFC 5161). 启用capability(请参阅RFC 5161)。Most capabilities do not need to be enabled. Currently only the UTF8=ACCEPT capability is supported (see RFC 6855).大多数功能都不需要启用。目前仅支持UTF8=ACCEPT功能(参见RFC 6855)。

New in version 3.5.版本3.5中新增。The enable() method itself, and RFC 6855 support.enable()方法本身,以及RFC 6855支持。

IMAP4.expunge()

Permanently remove deleted items from selected mailbox. 从选定邮箱中永久删除已删除的邮件。Generates an EXPUNGE response for each deleted message. 为每个删除的消息生成EXPUNGE响应。Returned data contains a list of EXPUNGE message numbers in order received.返回的数据包含按接收顺序排列的EXPUNGE消息编号列表。

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])". 应该是一个包含在括号内的消息部分名称字符串,例如:"(UID BODY[TEXT])"Returned data are tuples of message part envelope and data.返回的数据是消息部分信封和数据的元组。

IMAP4.getacl(mailbox)

Get the ACLs for mailbox. 获取mailboxACLThe method is non-standard, but is supported by the Cyrus server.该方法是非标准的,但受Cyrus服务器支持。

IMAP4.getannotation(mailbox, entry, attribute)

Retrieve the specified ANNOTATIONs for mailbox. 检索mailbox的指定ANNOTATIONThe method is non-standard, but is supported by the Cyrus server.该方法是非标准的,但受到Cyrus服务器的支持。

IMAP4.getquota(root)

Get the quota root’s resource usage and limits. 获取quotaroot的资源使用情况和限制。This method is part of the IMAP4 QUOTA extension defined in rfc2087.此方法是rfc2087中定义的IMAP4 QUOTA扩展的一部分。

IMAP4.getquotaroot(mailbox)

Get the list of quota roots for the named mailbox. 获取命名邮箱的quota roots目录列表。This method is part of the IMAP4 QUOTA extension defined in rfc2087.此方法是rfc2087中定义的IMAP4 QUOTA扩展的一部分。

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. directory匹配pattern列出邮箱名称。directory默认为顶级邮件文件夹,pattern默认为匹配任何内容。Returned data contains a list of LIST responses.返回的数据包含LIST响应的列表。

IMAP4.login(user, password)

Identify the client using a plaintext password. 使用明文密码识别客户端。The password will be quoted.password将被引用。

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.在识别客户端时强制使用CRAM-MD5身份验证来保护密码。仅当服务器CAPABILITY响应包含短语AUTH=CRAM-MD5时才有效。

IMAP4.logout()

Shutdown connection to server. 关闭与服务器的连接。Returns server BYE response.返回服务器BYE响应。

Changed in version 3.8:版本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. 默认为顶级目录,pattern默认为匹配任何邮箱。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).显示邮箱的ACL(即我对邮箱的权限)。

IMAP4.namespace()

Returns IMAP namespaces as defined in RFC 2342.返回RFC 2342中定义的IMAP命名空间。

IMAP4.noop()

Send NOOP to server.NOOP发送到服务器。

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

Opens socket to port at host. 打开到host port的套接字。The optional timeout parameter specifies a timeout in seconds for the connection attempt. 可选的timeout参数指定连接尝试的超时时间(以秒为单位)。If timeout is not given or is None, the global default socket timeout is used. 如果未给定timeout或为None,则使用全局默认套接字超时。Also note that if the timeout parameter is set to be zero, it will raise a ValueError to reject creating a non-blocking socket. This method is implicitly called by the IMAP4 constructor. 还要注意,如果timeout参数设置为零,它将引发ValueError以拒绝创建非阻塞套接字。此方法由IMAP4构造函数隐式调用。The connection objects established by this method will be used in the IMAP4.read(), IMAP4.readline(), IMAP4.send(), and IMAP4.shutdown() methods. 此方法建立的连接对象将用于IMAP4.read()IMAP4.readline()IMAP4.send()IMAP4.shutdown()方法。You may override this method.您可以覆盖此方法。

Raises an auditing event imaplib.open with arguments self, host, port.使用参数selfhostport引发审核事件imaplib.open

Changed in version 3.9:版本3.9中更改: The timeout parameter was added.已添加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. 假设身份验证为userAllows 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.从远程服务器读取size字节。您可以覆盖此方法。

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 response.如果没有新消息,返回的数据为None,否则为RECENT响应的值。

IMAP4.rename(oldmailbox, newmailbox)

Rename mailbox named oldmailbox to newmailbox.将名为oldmailbox的邮箱重命名为newmailbox

IMAP4.response(code)

Return data for response code if received, or None. 如果收到响应code,则返回数据,或者NoneReturns the given code, instead of the usual type.返回给定的代码,而不是通常的类型。

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

Search mailbox for matching messages. 在邮箱中搜索匹配的邮件。charset may be None, in which case no CHARSET will be specified in the request to the server. charset可以是None,在这种情况下,将不会在对服务器的请求中指定CHARSETThe IMAP protocol requires that at least one criterion be specified; an exception will be raised when the server returns an error. IMAP协议要求至少指定一个标准;当服务器返回错误时,将引发异常。charset must be None if the UTF8=ACCEPT capability was enabled using the enable() command.如果使用enable()命令启用了UTF8=ACCEPT功能,则charset必须为None

Example:实例

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

Select a mailbox. Returned data is the count of messages in mailbox (EXISTS response). 选择一个邮箱。返回的数据是mailbox中的邮件数(EXISTS响应)。The default mailbox is 'INBOX'. 默认mailbox'INBOX'If the readonly flag is set, modifications to the mailbox are not allowed.如果设置了readonly标志,则不允许修改邮箱。

IMAP4.send(data)

Sends data to the remote server. You may override this method.data发送到远程服务器。您可以覆盖此方法。

Raises an auditing event imaplib.send with arguments self, data.使用参数selfdata引发审核事件imaplib.send

IMAP4.setacl(mailbox, who, what)

Set an ACL for mailbox. mailbox设置ACLThe method is non-standard, but is supported by the Cyrus server.该方法是非标准的,但受到Cyrus服务器的支持。

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

Set ANNOTATIONs for mailbox. The method is non-standard, but is supported by the Cyrus server.设置mailboxANNOTATION。该方法是非标准的,但受到Cyrus服务器的支持。

IMAP4.setquota(root, limits)

Set the quota root’s resource limits. This method is part of the IMAP4 QUOTA extension defined in rfc2087.设置quota root的资源limits。此方法是rfc2087中定义的IMAP4 QUOTA扩展的一部分。

IMAP4.shutdown()

Close connection established in open. open状态下建立的关闭连接。This method is implicitly called by IMAP4.logout(). 此方法由IMAP4.logout()隐式调用。You may override this method.您可以覆盖此方法。

IMAP4.socket()

Returns socket instance used to connect to server.返回用于连接到服务器的套接字实例。

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

The sort command is a variant of search with sorting semantics for the results. sort命令是search的变体,具有对结果进行排序的语义。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, and the searching charset. Sort在search_criteration参数之前有两个参数;一个带括号的sort_criteria列表和搜索charsetNote that unlike search, the searching charset argument is mandatory. 请注意,与search不同,搜索charset参数是必需的。There is also a uid sort command which corresponds to sort the way that uid search corresponds to search. 还有一个uid sort命令,它对应于uid search对应于searchsort方式。The 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. sort命令首先使用字符集参数在邮箱中搜索与给定搜索条件匹配的邮件,该参数用于解释搜索条件中的字符串。It then returns the numbers of matching messages.然后返回匹配消息的数量。

This is an IMAP4rev1 extension command.这是一个IMAP4rev1扩展命令。

IMAP4.starttls(ssl_context=None)

Send a STARTTLS command. The ssl_context argument is optional and should be a ssl.SSLContext object. 发送STARTTLS命令。ssl_context参数是可选的,应该是ssl.SSLContext对象。This will enable encryption on the IMAP connection. 这将对IMAP连接启用加密。Please read Security considerations for best practices.请阅读最佳做法的安全注意事项

New in version 3.2.版本3.2中新增。

Changed in version 3.4:版本3.4中更改: The method now supports hostname check with ssl.SSLContext.check_hostname and Server Name Indication (see ssl.HAS_SNI).该方法现在支持使用ssl.SSLContext.check_hostnameServer Name Indication进行主机名检查(请参阅ssl.HAS_SNI)。

IMAP4.status(mailbox, names)

Request named status conditions for 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”.更改邮箱中邮件的标志配置。commandRFC 2060的6.4.6节指定为“FLAGS”、“+FLAGS”或“-FLAGS”之一,可选地带有后缀“SILENT”。

For example, to set the delete flag on all messages:例如,要在所有消息上设置删除标志:

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

Note

Creating flags containing ‘]’ (for example: “[test]”) violates RFC 3501 (the IMAP protocol). 创建包含']'的标志(例如:“[test]”)违反了RFC 3501(IMAP协议)。However, imaplib has historically allowed creation of such tags, and popular IMAP servers, such as Gmail, accept and produce such flags. 然而,imaplib在历史上允许创建这样的标签,而流行的IMAP服务器,如Gmail,接受并生成这样的标志。There are non-Python programs which also create such tags. 有些非Python程序也会创建这样的标记。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.尽管这违反了RFC,IMAP客户端和服务器应该是严格的,但出于向后兼容性的原因,imaplib仍然允许创建此类标签,并且从Python 3.6开始,如果这些标签是从服务器发送的,则会对其进行处理,因为这提高了现实世界的兼容性。

IMAP4.subscribe(mailbox)

Subscribe to new mailbox.订阅新邮箱。

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

The thread command is a variant of search with threading semantics for the results. thread命令是搜索结果的一种变体,具有线程语义。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, and the searching charset. 线程在search_criteration参数之前有两个参数;threading_algorithm和搜索charsetNote that unlike search, the searching charset argument is mandatory. 请注意,与search不同,搜索charset参数是必需的。There is also a uid thread command which corresponds to thread the way that uid search corresponds to search. 还有一个uid thread命令,它对应于thread,就像uid search对应于search一样。The 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. thread命令首先使用字符集参数在邮箱中搜索与给定搜索条件匹配的邮件,该参数用于解释搜索条件中的字符串。It then returns the matching messages threaded according to the specified threading algorithm.然后,它返回根据指定的线程算法进行线程处理的匹配消息。

This is an IMAP4rev1 extension command.这是一个IMAP4rev1扩展命令。

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

Execute command args with messages identified by UID, rather than message number. 使用由UID而不是消息编号标识的消息执行命令参数。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)

Unsubscribe from old 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.此命令执行与imaplib.IMAP4.close()相同的操作,只是不会从当前选定的邮箱中永久删除任何邮件。

New in version 3.9.版本3.9中新增。

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

Allow simple extension commands notified by server in CAPABILITY response.允许服务器在CAPABILITY响应中通知简单的扩展命令。

The following attributes are defined on instances of IMAP4:以下属性是在IMAP4实例上定义的:

IMAP4.PROTOCOL_VERSION

The most recent supported protocol in the CAPABILITY response from the server.来自服务器的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.初始化值取自模块变量Debug。大于三的值跟踪每个命令。

IMAP4.utf8_enabled

Boolean value that is normally False, but is set to True if an enable() command is successfully issued for the UTF8=ACCEPT capability.布尔值,通常为False,但如果为UTF8=ACCEPT功能成功发出enable()命令,则设置为True

New in version 3.5.版本3.5中新增。

IMAP4 Example

Here is a minimal example (without error checking) that opens a mailbox and retrieves and prints all messages:以下是一个打开邮箱并检索和打印所有邮件的最小示例(无需错误检查):

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