Python Network Programming 简明教程

Python - IMAP

IMAP 是一种不会下载电子邮件的电子邮件检索协议。它只是读取并显示电子邮件。这在小带宽条件下非常有用。Python 的名为 imaplib 的客户端库用于通过 IMAP 协议访问电子邮件。

IMAP is an email retrieval protocol which does not download the emails. It just reads them and displays them. This is very useful in low bandwidth condition. Python’s client side library called imaplib is used for accessing emails over imap protocol.

IMAP 代表 Internet Mail Access Protocol. ,它最早在 1986 年提出。

IMAP stands for Internet Mail Access Protocol. It was first proposed in 1986.

Key Points:

Key Points:

  1. IMAP allows the client program to manipulate the e-mail message on the server without downloading them on the local computer.

  2. The e-mail is hold and maintained by the remote server.

  3. It enables us to take any action such as downloading, delete the mail without reading the mail.It enables us to create, manipulate and delete remote message folders called mail boxes.

  4. IMAP enables the users to search the e-mails.

  5. It allows concurrent access to multiple mailboxes on multiple mail servers.

IMAP Commands

下表描述了一些 IMAP 命令:

The following table describes some of the IMAP commands:

S.N.

Command Description

1

IMAP_LOGIN This command opens the connection.

2

CAPABILITY This command requests for listing the capabilities that the server supports.

3

NOOP This command is used as a periodic poll for new messages or message status updates during a period of inactivity.

4

SELECT This command helps to select a mailbox to access the messages.

5

EXAMINE It is same as SELECT command except no change to the mailbox is permitted.

6

CREATE It is used to create mailbox with a specified name.

7

DELETE It is used to permanently delete a mailbox with a given name.

8

RENAME It is used to change the name of a mailbox.

9

LOGOUT This command informs the server that client is done with the session. The server must send BYE untagged response before the OK response and then close the network connection.

Example

在以下示例中,我们使用用户凭证登录到 gmail 服务器。然后,我们选择在收件箱中显示邮件。for 循环用于逐个显示已获取的邮件,最后关闭连接。

In the below example we login to a gmail server with user credentials. Then we choose to display the messages in the inbox. A for loop is used to display the fetched messages one by one and finally the connection is closed.

import imaplib
import pprint

imap_host = 'imap.gmail.com'
imap_user = 'username@gmail.com'
imap_pass = 'password'

# connect to host using SSL
imap = imaplib.IMAP4_SSL(imap_host)

## login to server
imap.login(imap_user, imap_pass)

imap.select('Inbox')

tmp, data = imap.search(None, 'ALL')
for num in data[0].split():
	tmp, data = imap.fetch(num, '(RFC822)')
	print('Message: {0}\n'.format(num))
	pprint.pprint(data[0][1])
	break
imap.close()

根据邮箱配置,显示邮件。

Depending on the mail box configuration, mail is displayed.