14.5. imaplib — imap4 客户端类库 | 邮件模块 |《python 3 标准库实例教程》| python 技术论坛-江南app体育官方入口

未匹配的标注

目的:用于imap4通信的客户端库。

imaplib实现用于与internet消息访问协议( imap )版本 4 服务器进行通信的客户端。 imap 协议定义了一组发送到服务器的命令以及将响应传递回客户端的命令。大多数命令可用作用于与服务器通信的imap4对象的方法。

这些示例讨论了 imap 协议的一部分,但绝不是完整的。有关完整的详细信息,请参阅 rfc 3501。

变化

存在三种用于使用各种机制与服务器进行通信的客户端类。第一个imap4使用明文套接字; imap4_ssl使用ssl套接字上的加密通信;和imap4_stream使用外部命令的标准输入和标准输出。此处所有示例将使用imap4_ssl,但其他类的 api 相似。

连接到服务器

与imap服务器建立连接有两个步骤。首先,设置套接字连接本身。其次,使用服务器上的帐户以用户身份进行身份验证。以下示例代码将从配置文件中读取服务器和用户信息。

imaplib_connect.py

import imaplib
import configparser
import os
def open_connection(verbose=false):
    # read the config file
    config = configparser.configparser()
    config.read([os.path.expanduser('~/.pymotw')])
    # connect to the server
    hostname = config.get('server', 'hostname')
    if verbose:
        print('connecting to', hostname)
    connection = imaplib.imap4_ssl(hostname)
    # login to our account
    username = config.get('account', 'username')
    password = config.get('account', 'password')
    if verbose:
        print('logging in as', username)
    connection.login(username, password)
    return connection
if __name__ == '__main__':
    with open_connection(verbose=true) as c:
        print(c)

运行时,open_connection()从用户主目录中的文件中读取配置信息,然后打开imap4_ssl连接并进行身份验证。

$ python3 imaplib_connect.py
connecting to pymotw.hellfly.net
logging in as example

本节中的其他示例重用了此模块,以避免重复代码。

验证失败

如果建立连接但身份验证失败,则会引发异常。

imaplib_connect_fail.py

import imaplib
import configparser
import os
# read the config file
config = configparser.configparser()
config.read([os.path.expanduser('~/.pymotw')])
# connect to the server
hostname = config.get('server', 'hostname')
print('connecting to', hostname)
connection = imaplib.imap4_ssl(hostname)
# login to our account
username = config.get('account', 'username')
password = 'this_is_the_wrong_password'
print('logging in as', username)
try:
    connection.login(username, password)
except exception as err:
    print('error:', err)

本示例故意使用错误的密码来触发异常。

$ python3 imaplib_connect_fail.py
connecting to pymotw.hellfly.net
logging in as example
error: b'[authenticationfailed] authentication failed.'

示例配置

该示例帐户在层次结构中具有多个邮箱:

  • inbox 收件箱
  • deleted messages 删除的邮件
  • archive 存档
  • example 例子
    • 2016

inbox文件夹中有一则未读消息,而example / 2016中有一则未读消息。

列出邮箱

要检索帐户可用的邮箱,请使用list()方法。

imaplib_list.py

import imaplib
from pprint import pprint
from imaplib_connect import open_connection
with open_connection() as c:
    typ, data = c.list()
    print('response code:', typ)
    print('response:')
    pprint(data)

返回值是一个tuple,包含响应代码和服务器返回的数据。除非出现错误,否则响应代码为oklist()的数据是一个字符串序列,包含每个邮箱的 标志,层次结构分隔符邮箱名称*。

$ python3 imaplib_list.py
response code: ok
response:
[b'(.haschildren) "." example',
 b'(.hasnochildren) "." example.2016',
 b'(.hasnochildren) "." archive',
 b'(.hasnochildren) "." "deleted messages"',
 b'(.hasnochildren) "." inbox']

每个响应字符串可以使用 或[ (请参阅 imap 本节末尾参考中的备份脚本,以使用csv的示例为例).

imaplib_list_parse.py

import imaplib
import re
from imaplib_connect import open_connection
list_response_pattern = re.compile(
    r'.(?p.*?). "(?p.*)" (?p.*)'
)
def parse_list_response(line):
    match = list_response_pattern.match(line.decode('utf-8'))
    flags, delimiter, mailbox_name = match.groups()
    mailbox_name = mailbox_name.strip('"')
    return (flags, delimiter, mailbox_name)
with open_connection() as c:
    typ, data = c.list()
print('response code:', typ)
for line in data:
    print('server response:', line)
    flags, delimiter, mailbox_name = parse_list_response(line)
    print('parsed response:', (flags, delimiter, mailbox_name))

如果服务器名称中包含空格,则服务器会引用该邮箱名称,但是稍后,需要删除那些引号,以便在其他回拨到服务器的调用中使用该邮箱名称。

$ python3 imaplib_list_parse.py
response code: ok
server response: b'(.haschildren) "." example'
parsed response: ('.haschildren', '.', 'example')
server response: b'(.hasnochildren) "." example.2016'
parsed response: ('.hasnochildren', '.', 'example.2016')
server response: b'(.hasnochildren) "." archive'
parsed response: ('.hasnochildren', '.', 'archive')
server response: b'(.hasnochildren) "." "deleted messages"'
parsed response: ('.hasnochildren', '.', 'deleted messages')
server response: b'(.hasnochildren) "." inbox'
parsed response: ('.hasnochildren', '.', 'inbox')

list()采用参数来指定部分层次结构中的邮箱。例如,要列出example的子文件夹,请传递“ example”作为目录参数。

imaplib_list_subfolders.py

import imaplib
from imaplib_connect import open_connection
with open_connection() as c:
    typ, data = c.list(directory='example')
print('response code:', typ)
for line in data:
    print('server response:', line)

返回父级和子文件夹。

$ python3 imaplib_list_subfolders.py
response code: ok
server response: b'(.haschildren) "." example'
server response: b'(.hasnochildren) "." example.2016'

或者,要列出与模式匹配的文件夹,请传递pattern参数。

imaplib_list_pattern.py

import imaplib
from imaplib_connect import open_connection
with open_connection() as c:
    typ, data = c.list(pattern='*example*')
print('response code:', typ)
for line in data:
    print('server response:', line)

在这种情况下,响应中同时包含exampleexample.2016

$ python3 imaplib_list_pattern.py
response code: ok
server response: b'(.haschildren) "." example'
server response: b'(.hasnochildren) "." example.2016'

邮箱状态

使用status()询问有关内容的汇总信息。下表列出了标准定义的状态条件。

imap 4邮箱状态条件

条件 含义
messages 邮箱中的邮件数。
recent 设置了.ecent标志的消息数。
uidnext 邮箱的下一个唯一标识符值。
uidvalidity 邮箱的唯一标识符有效性值。
unseen 没有设置.een标志的消息数。

状态条件的格式必须为括号内用空格分隔的字符串,这是imap4规范中“列表”的编码。邮箱名称被包裹在中,以防任何名称中包含空格或其他可能引发解析器的字符。

imaplib_status.py

import imaplib
import re
from imaplib_connect import open_connection
from imaplib_list_parse import parse_list_response
with open_connection() as c:
    typ, data = c.list()
    for line in data:
        flags, delimiter, mailbox = parse_list_response(line)
        print('mailbox:', mailbox)
        status = c.status(
            '"{}"'.format(mailbox),
            '(messages recent uidnext uidvalidity unseen)',
        )
        print(status)

返回值是通常的 tuple,其中包含响应代码和来自服务器的信息列表。在这种情况下,列表包含单个字符串,该字符串的格式为用引号引起来的邮箱名称,然后是括号中的状态条件和值。

$ python3 imaplib_status.py
response code: ok
server response: b'(.haschildren) "." example'
parsed response: ('.haschildren', '.', 'example')
server response: b'(.hasnochildren) "." example.2016'
parsed response: ('.hasnochildren', '.', 'example.2016')
server response: b'(.hasnochildren) "." archive'
parsed response: ('.hasnochildren', '.', 'archive')
server response: b'(.hasnochildren) "." "deleted messages"'
parsed response: ('.hasnochildren', '.', 'deleted messages')
server response: b'(.hasnochildren) "." inbox'
parsed response: ('.hasnochildren', '.', 'inbox')
mailbox: example
('ok', [b'example (messages 0 recent 0 uidnext 2 uidvalidity 145
7297771 unseen 0)'])
mailbox: example.2016
('ok', [b'example.2016 (messages 1 recent 0 uidnext 3 uidvalidit
y 1457297772 unseen 0)'])
mailbox: archive
('ok', [b'archive (messages 0 recent 0 uidnext 1 uidvalidity 145
7297770 unseen 0)'])
mailbox: deleted messages
('ok', [b'"deleted messages" (messages 3 recent 0 uidnext 4 uidv
alidity 1457297773 unseen 0)'])
mailbox: inbox
('ok', [b'inbox (messages 2 recent 0 uidnext 6 uidvalidity 14572
97769 unseen 1)'])

选择一个邮箱

客户端通过身份验证后,基本的操作模式是选择一个邮箱,然后向服务器询问有关邮箱中消息的信息。连接是有状态的,因此在选择邮箱后,所有命令都会对该邮箱中的消息进行操作,直到选择了新邮箱。

imaplib_select.py

import imaplib
import imaplib_connect
with imaplib_connect.open_connection() as c:
    typ, data = c.select('inbox')
    print(typ, data)
    num_msgs = int(data[0])
    print('there are {} messages in inbox'.format(num_msgs))

响应数据包含邮箱中的邮件总数。

$ python3 imaplib_select.py
ok [b'1']
there are 1 messages in inbox

如果指定了无效的邮箱,则响应代码为no

imaplib_select_invalid.py

import imaplib
import imaplib_connect
with imaplib_connect.open_connection() as c:
    typ, data = c.select('does-not-exist')
    print(typ, data)

数据包含描述该问题的错误消息。

$ python3 imaplib_select_invalid.py
no [b"mailbox doesn't exist: does-not-exist"]

搜索消息

选择邮箱后,使用search()检索邮箱中的邮件id。

imaplib_search_all.py

import imaplib
import imaplib_connect
from imaplib_list_parse import parse_list_response
with imaplib_connect.open_connection() as c:
    typ, mbox_data = c.list()
    for line in mbox_data:
        flags, delimiter, mbox_name = parse_list_response(line)
        c.select('"{}"'.format(mbox_name), readonly=true)
        typ, msg_ids = c.search(none, 'all')
        print(mbox_name, typ, msg_ids)

消息 id 由服务器分配,并且取决于实现。 imap4 协议区分了交易期间给定时间点的消息顺序 id 和消息的 uid 标识符,但并非所有服务器都实现这两者。

$ python3 imaplib_search_all.py
response code: ok
server response: b'(.haschildren) "." example'
parsed response: ('.haschildren', '.', 'example')
server response: b'(.hasnochildren) "." example.2016'
parsed response: ('.hasnochildren', '.', 'example.2016')
server response: b'(.hasnochildren) "." archive'
parsed response: ('.hasnochildren', '.', 'archive')
server response: b'(.hasnochildren) "." "deleted messages"'
parsed response: ('.hasnochildren', '.', 'deleted messages')
server response: b'(.hasnochildren) "." inbox'
parsed response: ('.hasnochildren', '.', 'inbox')
example ok [b'']
example.2016 ok [b'1']
archive ok [b'']
deleted messages ok [b'']
inbox ok [b'1']

在这种情况下,inboxexample.2016各自具有 id 为1的不同消息。其他邮箱为空。

搜索条件

可以使用各种其他搜索条件,包括查看消息的日期,标志和其他标题。请参阅 rfc 3501 第6.4.4 节 的完整细节。

要在主题中查找带有 'example message 2' 的消息,搜索条件应构造为:

(subject "example message 2")

本示例在所有邮箱中查找所有标题为 'example message 2' 的消息:

imaplib_search_subject.py

import imaplib
import imaplib_connect
from imaplib_list_parse import parse_list_response
with imaplib_connect.open_connection() as c:
    typ, mbox_data = c.list()
    for line in mbox_data:
        flags, delimiter, mbox_name = parse_list_response(line)
        c.select('"{}"'.format(mbox_name), readonly=true)
        typ, msg_ids = c.search(
            none,
            '(subject "example message 2")',
        )
        print(mbox_name, typ, msg_ids)

帐户中只有一条这样的消息,它在 inbox 中。

$ python3 imaplib_search_subject.py
response code: ok
server response: b'(.haschildren) "." example'
parsed response: ('.haschildren', '.', 'example')
server response: b'(.hasnochildren) "." example.2016'
parsed response: ('.hasnochildren', '.', 'example.2016')
server response: b'(.hasnochildren) "." archive'
parsed response: ('.hasnochildren', '.', 'archive')
server response: b'(.hasnochildren) "." "deleted messages"'
parsed response: ('.hasnochildren', '.', 'deleted messages')
server response: b'(.hasnochildren) "." inbox'
parsed response: ('.hasnochildren', '.', 'inbox')
example ok [b'']
example.2016 ok [b'']
archive ok [b'']
deleted messages ok [b'']
inbox ok [b'1']

搜索条件也可以组合。

imaplib_search_from.py

import imaplib
import imaplib_connect
from imaplib_list_parse import parse_list_response
with imaplib_connect.open_connection() as c:
    typ, mbox_data = c.list()
    for line in mbox_data:
        flags, delimiter, mbox_name = parse_list_response(line)
        c.select('"{}"'.format(mbox_name), readonly=true)
        typ, msg_ids = c.search(
            none,
            '(from "doug" subject "example message 2")',
        )
        print(mbox_name, typ, msg_ids)

这些标准与逻辑  and  运算结合在一起。

$ python3 imaplib_search_from.py
response code: ok
server response: b'(.haschildren) "." example'
parsed response: ('.haschildren', '.', 'example')
server response: b'(.hasnochildren) "." example.2016'
parsed response: ('.hasnochildren', '.', 'example.2016')
server response: b'(.hasnochildren) "." archive'
parsed response: ('.hasnochildren', '.', 'archive')
server response: b'(.hasnochildren) "." "deleted messages"'
parsed response: ('.hasnochildren', '.', 'deleted messages')
server response: b'(.hasnochildren) "." inbox'
parsed response: ('.hasnochildren', '.', 'inbox')
example ok [b'']
example.2016 ok [b'']
archive ok [b'']
deleted messages ok [b'']
inbox ok [b'1']

获取消息

search() 返回的标识符用于检索消息的内容或部分内容,以便使用 fetch() 方法进行进一步处理。它有两个参数,要获取的消息i d 和要检索的消息部分。

“ message_ids” 参数是逗号分隔的 id(例如“ 1”,“ 1,2””或 id 范围(例如“ 1:2”)列表。 message_parts 参数是消息段名称的imap列表。如同search()的搜索条件一样,imap 协议指定了命名的消息段,因此客户端可以有效地仅检索他们实际需要的消息部分。例如,要检索邮箱中邮件的标题,请使用带有参数body.peek [header] 的 fetch()

注意

另一种获取标头的方法是 body [headers] ,但是这种形式具有将消息隐式标记为已读的副作用,这在许多情况下是不希望的。

imaplib_fetch_raw.py

import imaplib
import pprint
import imaplib_connect
imaplib.debug = 4
with imaplib_connect.open_connection() as c:
    c.select('inbox', readonly=true)
    typ, msg_data = c.fetch('1', '(body.peek[header] flags)')
    pprint.pprint(msg_data)

fetch() 的返回值已经部分解析,因此使用起来比  list() 的返回值难一些。打开调试将显示客户端和服务器之间的完整交互,以了解为什么会这样。

$ python3 imaplib_fetch_raw.py
  19:40.68 imaplib version 2.58
  19:40.68 new imap4 connection, tag=b'iien'
  19:40.70 < b'* ok [capability imap4rev1 literal  sasl-ir login
-referrals id enable idle auth=plain] dovecot (ubuntu) ready.'
  19:40.70 > b'iien0 capability'
  19:40.73 < b'* capability imap4rev1 literal  sasl-ir login-ref
errals id enable idle auth=plain'
  19:40.73 < b'iien0 ok pre-login capabilities listed, post-logi
n capabilities have more.'
  19:40.73 capabilities: ('imap4rev1', 'literal ', 'sasl-ir', 'l
ogin-referrals', 'id', 'enable', 'idle', 'auth=plain')
  19:40.73 > b'iien1 login example "tmfw00fpymotw"'
  19:40.79 < b'* capability imap4rev1 literal  sasl-ir login-ref
errals id enable idle sort sort=display thread=references thread
=refs thread=orderedsubject multiappend url-partial catenate uns
elect children namespace uidplus list-extended i18nlevel=1 conds
tore qresync esearch esort searchres within context=search list-
status special-use binary move'
  19:40.79 < b'iien1 ok logged in'
  19:40.79 > b'iien2 examine inbox'
  19:40.82 < b'* flags (.answered .flagged .deleted .seen .
draft)'
  19:40.82 < b'* ok [permanentflags ()] read-only mailbox.'
  19:40.82 < b'* 2 exists'
  19:40.82 < b'* 0 recent'
  19:40.82 < b'* ok [unseen 1] first unseen.'
  19:40.82 < b'* ok [uidvalidity 1457297769] uids valid'
  19:40.82 < b'* ok [uidnext 6] predicted next uid'
  19:40.82 < b'* ok [highestmodseq 20] highest'
  19:40.82 < b'iien2 ok [read-only] examine completed (0.000 sec
s).'
  19:40.82 > b'iien3 fetch 1 (body.peek[header] flags)'
  19:40.86 < b'* 1 fetch (flags () body[header] {3108}'
  19:40.86 read literal size 3108
  19:40.86 < b')'
  19:40.89 < b'iien3 ok fetch completed.'
  19:40.89 > b'iien4 logout'
  19:40.93 < b'* bye logging out'
  19:40.93 bye response: b'logging out'
[(b'1 (flags () body[header] {3108}',
  b'return-path: <[email protected]>..received: from compu
te4.internal ('
  b'compute4.nyi.internal [10.202.2.44])... by sloti26t01 (cy
rus 3.0.0-beta1'
  b'-git-fastmail-12410) with lmtpa;... sun, 06 mar 2016 16:1
6:03 -0500.'
  b'.x-sieve: cmu sieve 2.4..x-spam-known-sender: yes, fadd1c
f2-dc3a-4984-a0'
  b'8b-02cef3cf1221="doug",..  ea349ad0-9299-47b5-b632-6ff1e39
4cc7d="both he'
  b'llfly"..x-spam-score: 0.0..x-spam-hits: all_trusted -1,
bayes_00 -1.'
  b'9, languages unknown, bayes_used global,..  sa_version 3.3
.2..x-spam'
  b"-source: ip='127.0.0.1', host='unk', country='unk', fromhead
er='com',.. "
  b" mailfrom='com'..x-spam-charsets: plain='us-ascii'..x-re
solved-to: d"
  b'[email protected]: doug@doughellmann
.com..x-ma'
  b'il-from: [email protected]: from mx5 ([10.20
2.2.204]).'
  b'.  by compute4.internal (lmtpproxy); sun, 06 mar 2016 16:16
:03 -0500..re'
  b'ceived: from mx5.nyi.internal (localhost [127.0.0.1])...b
y mx5.nyi.inter'
  b'nal (postfix) with esmtp id 47cba280db3...for ; s'
  b'un,  6 mar 2016 16:16:03 -0500 (est)..received: from mx5.n
yi.internal (l'
  b'ocalhost [127.0.0.1])..    by mx5.nyi.internal (authentica
tion milter) w'
  b'ith esmtp..    id a717886846e.30ba4280d81;..    sun, 6 m
ar 2016 16:1'
  b'6:03 -0500..authentication-results: mx5.nyi.internal;..
   dkim=pass'
  b' (1024-bit rsa key) header.d=messagingengine.com header.i=@m
essagingengi'
  b'ne.com header.b=jrsm pco;..    x-local-ip=pass..received
: from mailo'
  b'ut.nyi.internal (gateway1.nyi.internal [10.202.2.221])...
(using tlsv1.2 '
  b'with cipher ecdhe-rsa-aes256-gcm-sha384 (256/256 bits))..
t(no client cer'
  b'tificate requested)...by mx5.nyi.internal (postfix) with
esmtps id 30ba4'
  b'280d81...for <[email protected]>; sun,  6 mar 2016 16
:16:03 -0500 (e'
  b'st)..received: from compute2.internal (compute2.nyi.intern
al [10.202.2.4'
  b'2])...by mailout.nyi.internal (postfix) with esmtp id 174
0420d0a...f'
  b'or <[email protected]>; sun,  6 mar 2016 16:16:03 -0500
(est)..recei'
  b'ved: from frontend2 ([10.202.2.161])..  by compute2.intern
al (meproxy); '
  b'sun, 06 mar 2016 16:16:03 -0500..dkim-signature: v=1; a=rs
a-sha1; c=rela'
  b'xed/relaxed; d=...messagingengine.com; h=content-transfer
-encoding:conte'
  b'nt-type...:date:from:message-id:mime-version:subject:to:x
-sasl-enc..'
  b'.:x-sasl-enc; s=smtpout; bh=p98ntseo015suwj4gk71knawla4=; b
=jrsm ...'
  b'pcovrioqiryp8fl0l6jhoi8sbzy2obx7o28jf2itltwmx33rhlq9403xrklw
n3ja...7kspq'
  b'mtp30qdx6yiuaadwqqlo qmuqq/qxbhdjeebmdhgvfjhqxrztbsmww/znhl
r..ywv/qm/odh'
  b'bxilsulb3qrg 9wse/0ju/eoisiu=..x-sasl-enc: 8zj 4zre8agpzdl
rwqfivgymjb8pa'
  b'4g9jgcb7k4xkn i 1457298962..received: from [192.168.1.14]
(75-137-1-34.d'
  b'hcp.nwnn.ga.charter.com [75.137.1.34])...by mail.messagin
gengine.com (po'
  b'stfix) with esmtpa id c0b366801cd...for ; sun,  6'
  b' mar 2016 16:16:02 -0500 (est)..from: doug hellmann ..content-type: text/plain; charset=us-ascii..content
-transfer-en'
  b'coding: 7bit..subject: pymotw example message 2..message
-id: <00abcd'
  b'[email protected]>..date: su
n, 6 mar 2016 '
  b'16:16:02 -0500..to: doug hellmann <[email protected]>
r.mime-vers'
  b'ion: 1.0 (mac os x mail 9.2 .(3112.))..x-mailer: apple m
ail (2.3112)'
  b'....'),
 b')']

 fetch 命令的响应从标志开始,然后指示头数据有595字节。 客户端使用消息的响应构造一个元组,然后用包含右括号 (“)”) 的单个字符串关闭该序列,服务器在获取响应的末尾发送该字符串。 由于采用这种格式,可能更容易分别获取不同的信息,或者重新组合响应并在客户端中对其进行解析。

imaplib_fetch_separately.py

import imaplib
import pprint
import imaplib_connect
with imaplib_connect.open_connection() as c:
    c.select('inbox', readonly=true)
    print('header:')
    typ, msg_data = c.fetch('1', '(body.peek[header])')
    for response_part in msg_data:
        if isinstance(response_part, tuple):
            print(response_part[1])
    print('.body text:')
    typ, msg_data = c.fetch('1', '(body.peek[text])')
    for response_part in msg_data:
        if isinstance(response_part, tuple):
            print(response_part[1])
    print('.flags:')
    typ, msg_data = c.fetch('1', '(flags)')
    for response_part in msg_data:
        print(response_part)
        print(imaplib.parseflags(response_part))

分别获取值还有一个额外的好处,就是易于使用  parseflags() 从响应中解析标志。

$ python3 imaplib_fetch_separately.py
header:
b'return-path: <[email protected]>..received: from compute
4.internal (compute4.nyi.internal [10.202.2.44])... by sloti2
6t01 (cyrus 3.0.0-beta1-git-fastmail-12410) with lmtpa;... su
n, 06 mar 2016 16:16:03 -0500..x-sieve: cmu sieve 2.4..x-spa
m-known-sender: yes, fadd1cf2-dc3a-4984-a08b-02cef3cf1221="doug"
,..  ea349ad0-9299-47b5-b632-6ff1e394cc7d="both hellfly"..x-
spam-score: 0.0..x-spam-hits: all_trusted -1, bayes_00 -1.9, l
anguages unknown, bayes_used global,..  sa_version 3.3.2..x-
spam-source: ip=.127.0.0.1., host=.unk., country=.unk., fr
omheader=.com.,..  mailfrom=.com...x-spam-charsets: plai
n=.us-ascii...x-resolved-to: [email protected]
elivered-to: [email protected]: doug@doughell
mann.com..received: from mx5 ([10.202.2.204])..  by compute4
.internal (lmtpproxy); sun, 06 mar 2016 16:16:03 -0500..receiv
ed: from mx5.nyi.internal (localhost [127.0.0.1])...by mx5.ny
i.internal (postfix) with esmtp id 47cba280db3...for ; sun,  6 mar 2016 16:16:03 -0500 (est)..receiv
ed: from mx5.nyi.internal (localhost [127.0.0.1])..    by mx5.
nyi.internal (authentication milter) with esmtp..    id a71788
6846e.30ba4280d81;..    sun, 6 mar 2016 16:16:03 -0500..auth
entication-results: mx5.nyi.internal;..    dkim=pass (1024-bit
 rsa key) header.d=messagingengine.com header.i=@messagingengine
.com header.b=jrsm pco;..    x-local-ip=pass..received: from
 mailout.nyi.internal (gateway1.nyi.internal [10.202.2.221])..
.(using tlsv1.2 with cipher ecdhe-rsa-aes256-gcm-sha384 (256/25
6 bits))...(no client certificate requested)...by mx5.nyi.
internal (postfix) with esmtps id 30ba4280d81...for ; sun,  6 mar 2016 16:16:03 -0500 (est)..receive
d: from compute2.internal (compute2.nyi.internal [10.202.2.42])
r..by mailout.nyi.internal (postfix) with esmtp id 1740420d0a
r..for <[email protected]>; sun,  6 mar 2016 16:16:03 -050
0 (est)..received: from frontend2 ([10.202.2.161])..  by com
pute2.internal (meproxy); sun, 06 mar 2016 16:16:03 -0500..dki
m-signature: v=1; a=rsa-sha1; c=relaxed/relaxed; d=...messagi
ngengine.com; h=content-transfer-encoding:content-type...:dat
e:from:message-id:mime-version:subject:to:x-sasl-enc...:x-sas
l-enc; s=smtpout; bh=p98ntseo015suwj4gk71knawla4=; b=jrsm ...
pcovrioqiryp8fl0l6jhoi8sbzy2obx7o28jf2itltwmx33rhlq9403xrklwn3ja
...7kspqmtp30qdx6yiuaadwqqlo qmuqq/qxbhdjeebmdhgvfjhqxrztbsmw
w/znhl...ywv/qm/odhbxilsulb3qrg 9wse/0ju/eoisiu=..x-sasl-en
c: 8zj 4zre8agpzdlrwqfivgymjb8pa4g9jgcb7k4xkn i 1457298962..re
ceived: from [192.168.1.14] (75-137-1-34.dhcp.nwnn.ga.charter.co
m [75.137.1.34])...by mail.messagingengine.com (postfix) with
 esmtpa id c0b366801cd...for <[email protected]>; sun,  6
 mar 2016 16:16:02 -0500 (est)..from: doug hellmann ..content-type: text/plain; charset=us-ascii..c
ontent-transfer-encoding: 7bit..subject: pymotw example messag
e 2..message-id: <00abcd46-dada-4912-a451-d27165bc3a2f@doughel
lmann.com>..date: sun, 6 mar 2016 16:16:02 -0500..to: doug h
ellmann <[email protected]>..mime-version: 1.0 (mac os x m
ail 9.2 .(3112.))..x-mailer: apple mail (2.3112)....'
body text:
b'this is the second example message...'
flags:
b'1 (flags ())'
()

全部消息

如前所述,客户端可以分别向服务器询问消息的各个部分。还可以将整个消息作为 rfc 822 格式的邮件消息进行检索,并使用email模块中的类对其进行解析。

imaplib_fetch_rfc822.py

import imaplib
import email
import email.parser
import imaplib_connect
with imaplib_connect.open_connection() as c:
    c.select('inbox', readonly=true)
    typ, msg_data = c.fetch('1', '(rfc822)')
    for response_part in msg_data:
        if isinstance(response_part, tuple):
            email_parser = email.parser.bytesfeedparser()
            email_parser.feed(response_part[1])
            msg = email_parser.close()
            for header in ['subject', 'to', 'from']:
                print('{:^8}: {}'.format(
                    header.upper(), msg[header]))

email 模块中的解析器使访问和处理消息变得非常容易。本示例仅为每个消息打印一些标题。

$ python3 imaplib_fetch_rfc822.py
subject : pymotw example message 2
   to   : doug hellmann <[email protected]>
  from  : doug hellmann <[email protected]>

上传消息

要将新邮件添加到邮箱,请构造一个message实例,并将其以及该邮件的时间戳传递给append() 方法。

imaplib_append.py

import imaplib
import time
import email.message
import imaplib_connect
new_message = email.message.message()
new_message.set_unixfrom('pymotw')
new_message['subject'] = 'subject goes here'
new_message['from'] = '[email protected]'
new_message['to'] = '[email protected]'
new_message.set_payload('this is the body of the message..')
print(new_message)
with imaplib_connect.open_connection() as c:
    c.append('inbox', '',
             imaplib.time2internaldate(time.time()),
             str(new_message).encode('utf-8'))
    # show the headers for all messages in the mailbox
    c.select('inbox')
    typ, [msg_ids] = c.search(none, 'all')
    for num in msg_ids.split():
        typ, msg_data = c.fetch(num, '(body.peek[header])')
        for response_part in msg_data:
            if isinstance(response_part, tuple):
                print('.{}:'.format(num))
                print(response_part[1])

本示例中使用的  payload  是一个简单的纯文本电子邮件正文。 message还支持mime编码的多部分消息。

$ python3 imaplib_append.py
subject: subject goes here
from: [email protected]
to: [email protected]
this is the body of the message.
b'1':
b'return-path: <[email protected]>..received: from compute
4.internal (compute4.nyi.internal [10.202.2.44])... by sloti2
6t01 (cyrus 3.0.0-beta1-git-fastmail-12410) with lmtpa;... su
n, 06 mar 2016 16:16:03 -0500..x-sieve: cmu sieve 2.4..x-spa
m-known-sender: yes, fadd1cf2-dc3a-4984-a08b-02cef3cf1221="doug"
,..  ea349ad0-9299-47b5-b632-6ff1e394cc7d="both hellfly"..x-
spam-score: 0.0..x-spam-hits: all_trusted -1, bayes_00 -1.9, l
anguages unknown, bayes_used global,..  sa_version 3.3.2..x-
spam-source: ip=.127.0.0.1., host=.unk., country=.unk., fr
omheader=.com.,..  mailfrom=.com...x-spam-charsets: plai
n=.us-ascii...x-resolved-to: [email protected]
elivered-to: [email protected]: doug@doughell
mann.com..received: from mx5 ([10.202.2.204])..  by compute4
.internal (lmtpproxy); sun, 06 mar 2016 16:16:03 -0500..receiv
ed: from mx5.nyi.internal (localhost [127.0.0.1])...by mx5.ny
i.internal (postfix) with esmtp id 47cba280db3...for ; sun,  6 mar 2016 16:16:03 -0500 (est)..receiv
ed: from mx5.nyi.internal (localhost [127.0.0.1])..    by mx5.
nyi.internal (authentication milter) with esmtp..    id a71788
6846e.30ba4280d81;..    sun, 6 mar 2016 16:16:03 -0500..auth
entication-results: mx5.nyi.internal;..    dkim=pass (1024-bit
 rsa key) header.d=messagingengine.com header.i=@messagingengine
.com header.b=jrsm pco;..    x-local-ip=pass..received: from
 mailout.nyi.internal (gateway1.nyi.internal [10.202.2.221])..
.(using tlsv1.2 with cipher ecdhe-rsa-aes256-gcm-sha384 (256/25
6 bits))...(no client certificate requested)...by mx5.nyi.
internal (postfix) with esmtps id 30ba4280d81...for ; sun,  6 mar 2016 16:16:03 -0500 (est)..receive
d: from compute2.internal (compute2.nyi.internal [10.202.2.42])
r..by mailout.nyi.internal (postfix) with esmtp id 1740420d0a
r..for <[email protected]>; sun,  6 mar 2016 16:16:03 -050
0 (est)..received: from frontend2 ([10.202.2.161])..  by com
pute2.internal (meproxy); sun, 06 mar 2016 16:16:03 -0500..dki
m-signature: v=1; a=rsa-sha1; c=relaxed/relaxed; d=...messagi
ngengine.com; h=content-transfer-encoding:content-type...:dat
e:from:message-id:mime-version:subject:to:x-sasl-enc...:x-sas
l-enc; s=smtpout; bh=p98ntseo015suwj4gk71knawla4=; b=jrsm ...
pcovrioqiryp8fl0l6jhoi8sbzy2obx7o28jf2itltwmx33rhlq9403xrklwn3ja
...7kspqmtp30qdx6yiuaadwqqlo qmuqq/qxbhdjeebmdhgvfjhqxrztbsmw
w/znhl...ywv/qm/odhbxilsulb3qrg 9wse/0ju/eoisiu=..x-sasl-en
c: 8zj 4zre8agpzdlrwqfivgymjb8pa4g9jgcb7k4xkn i 1457298962..re
ceived: from [192.168.1.14] (75-137-1-34.dhcp.nwnn.ga.charter.co
m [75.137.1.34])...by mail.messagingengine.com (postfix) with
 esmtpa id c0b366801cd...for <[email protected]>; sun,  6
 mar 2016 16:16:02 -0500 (est)..from: doug hellmann ..content-type: text/plain; charset=us-ascii..c
ontent-transfer-encoding: 7bit..subject: pymotw example messag
e 2..message-id: <00abcd46-dada-4912-a451-d27165bc3a2f@doughel
lmann.com>..date: sun, 6 mar 2016 16:16:02 -0500..to: doug h
ellmann <[email protected]>..mime-version: 1.0 (mac os x m
ail 9.2 .(3112.))..x-mailer: apple mail (2.3112)....'
b'2':
b'subject: subject goes here..from: [email protected]:
[email protected]....'

移动和复制消息

消息在服务器上后,可以使用move()copy()将其移动或复制而无需下载。这些方法对消息id范围进行操作,就像fetch()一样。

imaplib_archive_read.py

import imaplib
import imaplib_connect
with imaplib_connect.open_connection() as c:
    # find the "seen" messages in inbox
    c.select('inbox')
    typ, [response] = c.search(none, 'seen')
    if typ != 'ok':
        raise runtimeerror(response)
    msg_ids = ','.join(response.decode('utf-8').split(' '))
    # create a new mailbox, "example.today"
    typ, create_response = c.create('example.today')
    print('created example.today:', create_response)
    # copy the messages
    print('copying:', msg_ids)
    c.copy(msg_ids, 'example.today')
    # look at the results
    c.select('example.today')
    typ, [response] = c.search(none, 'all')
    print('copied:', response)

该示例脚本在example下创建一个新邮箱,并将读取的邮件从inbox复制到其中。

$ python3 imaplib_archive_read.py
created example.today: [b'completed']
copying: 2
copied: b'1'

再次运行同一脚本显示了检查返回码的重要性。除了引发异常外,对create() 的调用使新邮箱报告该邮箱已存在。

$ python3 imaplib_archive_read.py
created example.today: [b'[alreadyexists] mailbox already exists
']
copying: 2
copied: b'1 2'

删除讯息

尽管许多现代邮件客户端使用“垃圾箱”模型来处理已删除的邮件,但通常不会将邮件移到实际的文件夹中。而是更新其标志以添加.eleted。通过expunge命令实现“清空”垃圾的操作。此示例脚本查找主题中带有“ lorem ipsum ”的已归档邮件,设置已删除标志,然后通过再次查询服务器来显示邮件仍存在于文件夹中。

imaplib_delete_messages.py

import imaplib
import imaplib_connect
from imaplib_list_parse import parse_list_response
with imaplib_connect.open_connection() as c:
    c.select('example.today')
    # what ids are in the mailbox?
    typ, [msg_ids] = c.search(none, 'all')
    print('starting messages:', msg_ids)
    # find the message(s)
    typ, [msg_ids] = c.search(
        none,
        '(subject "subject goes here")',
    )
    msg_ids = ','.join(msg_ids.decode('utf-8').split(' '))
    print('matching messages:', msg_ids)
    # what are the current flags?
    typ, response = c.fetch(msg_ids, '(flags)')
    print('flags before:', response)
    # change the deleted flag
    typ, response = c.store(msg_ids, ' flags', r'(.eleted)')
    # what are the flags now?
    typ, response = c.fetch(msg_ids, '(flags)')
    print('flags after:', response)
    # really delete the message.
    typ, response = c.expunge()
    print('expunged:', response)
    # what ids are left in the mailbox?
    typ, [msg_ids] = c.search(none, 'all')
    print('remaining messages:', msg_ids)

显式调用expunge()会删除消息,但是调用close()具有相同的效果。区别在于调用close()时不会通知客户端有关删除的操作。

$ python3 imaplib_delete_messages.py
response code: ok
server response: b'(.haschildren) "." example'
parsed response: ('.haschildren', '.', 'example')
server response: b'(.hasnochildren) "." example.today'
parsed response: ('.hasnochildren', '.', 'example.today')
server response: b'(.hasnochildren) "." example.2016'
parsed response: ('.hasnochildren', '.', 'example.2016')
server response: b'(.hasnochildren) "." archive'
parsed response: ('.hasnochildren', '.', 'archive')
server response: b'(.hasnochildren) "." "deleted messages"'
parsed response: ('.hasnochildren', '.', 'deleted messages')
server response: b'(.hasnochildren) "." inbox'
parsed response: ('.hasnochildren', '.', 'inbox')
starting messages: b'1 2'
matching messages: 1,2
flags before: [b'1 (flags (.seen))', b'2 (flags (.seen))']
flags after: [b'1 (flags (.deleted .seen))', b'2 (flags (.del
eted .seen))']
expunged: [b'2', b'1']
remaining messages: b''

另请参见

  • rfc822rfc822模块包含 rfc 822 / rfc 5322 解析器。
  • email – 用于解析电子邮件的 e-mail 模块。
  •  –本地邮箱解析器。
  • configparser – 读取和写入配置文件。
  •  – imap信息的良好资源以及源代码。
  •  – nternet邮件访问协议
  •  – internet邮件格式
  •  – 用于从imap服务器备份电子邮件的脚本。
  •  – 由menno smits编写的用于与imap服务器对话的高级客户端。
  •  – 一种python应用程序,用于使本地邮箱组与imap服务器保持同步。

本文章首发在 江南app体育官方入口 网站上。

本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 cc 协议,如果我们的工作有侵犯到您的权益,请及时联系江南app体育官方入口。

原文地址:https://learnku.com/docs/pymotw/imaplib-...

译文地址:https://learnku.com/docs/pymotw/imaplib-...

上一篇 下一篇
贡献者:1
讨论数量: 0



暂无话题~
网站地图