imaplib
— IMAP4 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. IMAP4
、IMAP4_SSL
和IMAP4_stream
,它们封装了与IMAP4服务器的连接,并实现了RFC 2060中定义的IMAP4rev1客户端协议的一大部分。It is backward compatible with IMAP4 (RFC 1730) servers, but note that the 它与IMAP4(RFC 1730)服务器向后兼容,但请注意,IMAP4不支持STATUS命令。STATUS
command is not supported in IMAP4.
Three classes are provided by the imaplib
module, IMAP4
is the base class:imaplib
模块提供三个类,IMAP4
是基类:
-
class
imaplib.
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,如果未指定host,则使用''
(the local host) is used.''
(本地主机)。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,则使用全局默认套接字超时。TheIMAP4
class supports thewith
statement. When used like this, the IMAP4LOGOUT
command is issued automatically when thewith
statement exits. E.g.:IMAP4
类支持with
语句。这样使用时,当with
语句退出时,IMAP4LOGOUT
命令会自动发出。如。:>>> from imaplib import IMAP4
>>> with IMAP4("domain.org") as M:
... M.noop()
...
('OK', [b'Nothing Accomplished. d25if65hy903weo.87'])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
类的属性定义了三个例外:
-
exception
IMAP4.
error
¶ Exception raised on any errors.出现任何错误时出现异常。The reason for the exception is passed to the constructor as a string.异常的原因以字符串的形式传递给构造函数。
-
exception
IMAP4.
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.请注意,关闭实例并实例化新实例通常会允许从此异常中恢复。
-
exception
IMAP4.
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:还有一个子类用于安全连接:
-
class
imaplib.
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,如果未指定host,则使用''
(the local host) is used.''
(本地主机)。If port is omitted, the standard IMAP4-over-SSL port (993) is used.如果省略port,则使用标准的IMAP4 over SSL端口(993)。ssl_contextis 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.keyfile和certfile是ssl_context的遗留替代方案,它们可以指向ssl连接的PEM格式的私钥和证书链文件。Note that the keyfile/certfile parameters are mutually exclusive with ssl_context, a请注意,keyfile/certfile参数与ssl_context互斥,如果keyfile/cert文件与ssl_cntext一起提供,则会引发ValueError
is raised if keyfile/certfile is provided along with ssl_context.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 (seessl.HAS_SNI
).ssl.SSLContext.check_hostname
和Server Name Indication进行主机名检查(请参阅ssl.HAS_SNI
)。Deprecated since version 3.6:自3.6版以来已弃用:keyfile and certfile are deprecated in favor of ssl_context.不赞成使用keyfile和certfile,而赞成使用ssl_context。Please use请改用ssl.SSLContext.load_cert_chain()
instead, or letssl.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:第二个子类允许子进程创建连接:
-
class
imaplib.
IMAP4_stream
(command)¶ This is a subclass derived from这是从IMAP4
that connects to thestdin/stdout
file descriptors created by passing command tosubprocess.Popen()
.IMAP4
派生的子类,它连接到通过将命令传递给subprocess.Popen()
创建的stdin/stdout
文件描述符。
The following utility functions are defined:定义了以下实用程序函数:
-
imaplib.
Internaldate2tuple
(datestr)¶ Parse an IMAP4分析IMAP4INTERNALDATE
string and return corresponding local time.INTERNALDATE
字符串并返回相应的本地时间。The return value is a如果字符串格式错误,则返回值为time.struct_time
tuple orNone
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将IMAP4FLAGS
response to a tuple of individual flags.FLAGS
响应转换为单个标志的元组。
-
imaplib.
Time2Internaldate
(date_time)¶ Convert date_time to an IMAP4将date_time转换为IMAP4INTERNALDATE
representation.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 bydate_time参数可以是表示自epoch以来的秒数的数字(int或float)(由time.time()
), a 9-tuple representing local time an instance oftime.struct_time
(as returned bytime.localtime()
), an aware instance ofdatetime.datetime
, or a double-quoted string.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 请注意,IMAP4消息编号会随着邮箱的变化而变化;特别是,在EXPUNGE
command performs deletions the remaining messages are renumbered. 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)'
).STORE
的flags参数),请将字符串括在括号中(例如: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 每个data要么是bytes
, or a tuple. 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 formAUTH=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它将被调用来处理服务器继续响应;它传递的response参数将是bytes
.bytes
。It 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)。
-
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_partsshould 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获取mailbox的ACL
s for mailbox.ACL
。The method is non-standard, but is supported by the该方法是非标准的,但受Cyrus
server.Cyrus
服务器支持。
-
IMAP4.
getannotation
(mailbox, entry, attribute)¶ Retrieve the specified检索mailbox的指定ANNOTATION
s for mailbox.ANNOTATION
。The method is non-standard, but is supported by the该方法是非标准的,但受到Cyrus
server.Cyrus
服务器的支持。
-
IMAP4.
getquota
(root)¶ Get the获取quota
root’s resource usage and limits.quota
root的资源使用情况和限制。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 serverCAPABILITY
response includes the phraseAUTH=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.以目录匹配模式列出订阅的邮箱名称。directorydefaults 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.
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还要注意,如果timeout参数设置为零,它将引发ValueError
to reject creating a non-blocking socket. This method is implicitly called by theIMAP4
constructor.ValueError
以拒绝创建非阻塞套接字。此方法由IMAP4
构造函数隐式调用。The connection objects established by this method will be used in the此方法建立的连接对象将用于IMAP4.read()
,IMAP4.readline()
,IMAP4.send()
, andIMAP4.shutdown()
methods.IMAP4.read()
、IMAP4.readline()
、IMAP4.send()
和IMAP4.shutdown()
方法。You may override this method.您可以覆盖此方法。Raises an auditing event使用参数imaplib.open
with argumentsself
,host
,port
.self
、host
、port
引发审核事件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.假设身份验证为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.从远程服务器读取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 ofRECENT
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如果收到响应code,则返回数据,或者None
.None
。Returns the given code, instead of the usual type.返回给定的代码,而不是通常的类型。
-
IMAP4.
search
(charset, criterion[, ...])¶ Search mailbox for matching messages.在邮箱中搜索匹配的邮件。charset may becharset可以是None
, in which case noCHARSET
will be specified in the request to the server.None
,在这种情况下,将不会在对服务器的请求中指定CHARSET
。The 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 theUTF8=ACCEPT
capability was enabled using theenable()
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 (选择一个邮箱。返回的数据是mailbox中的邮件数(EXISTS
response).EXISTS
响应)。The default mailbox is默认mailbox为'INBOX'
.'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 argumentsself
,data
.self
、data
引发审核事件imaplib.send
。
-
IMAP4.
setacl
(mailbox, who, what)¶ Set an为mailbox设置ACL
for mailbox.ACL
。The method is non-standard, but is supported by the该方法是非标准的,但受到Cyrus
server.Cyrus
服务器的支持。
-
IMAP4.
setannotation
(mailbox, entry, attribute[, ...])¶ Set设置mailbox的ANNOTATION
s for mailbox. The method is non-standard, but is supported by theCyrus
server.ANNOTATION
。该方法是非标准的,但受到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[, ...])¶ Thesort
command is a variant ofsearch
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列表和搜索charset。Note that unlike请注意,与search
, the searching charset argument is mandatory.search
不同,搜索charset参数是必需的。There is also a还有一个uid sort
command which corresponds tosort
the way thatuid search
corresponds tosearch
.uid sort
命令,它对应于uid search
对应于search
的sort
方式。Thesort
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 assl.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 (seessl.HAS_SNI
).ssl.SSLContext.check_hostname
和Server 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”.更改邮箱中邮件的标志配置。command由RFC 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[, ...])¶ Thethread
command is a variant ofsearch
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和搜索charset。Note that unlike请注意,与search
, the searching charset argument is mandatory.search
不同,搜索charset参数是必需的。There is also a还有一个uid thread
command which corresponds tothread
the way thatuid search
corresponds tosearch
.uid thread
命令,它对应于thread
,就像uid search
对应于search
一样。Thethread
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 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()