📜  Python -IMAP

📅  最后修改于: 2020-11-06 06:33:46             🧑  作者: Mango


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

IMAP代表Internet邮件访问协议。它是在1986年首次提出的。

关键点:

  • IMAP允许客户端程序在服务器上处理电子邮件,而无需在本地计算机上下载它们。

  • 该电子邮件由远程服务器保留和维护。

  • 它使我们能够执行任何操作,例如下载,删除邮件而不阅读邮件。它使我们能够创建,操作和删除称为邮箱的远程消息文件夹。

  • IMAP使用户可以搜索电子邮件。

  • 它允许并发访问多个邮件服务器上的多个邮箱。

IMAP命令

下表描述了一些IMAP命令:

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.

在下面的示例中,我们使用用户凭据登录到Gmail服务器。然后,我们选择在收件箱中显示消息。使用for循环逐个显示获取的消息,最后关闭连接。

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

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