Python Network Programming 简明教程

Python - POP3

pop3 协议是一个电子邮件协议,用于从电子邮件服务器下载邮件。这些消息可以存储在本地计算机中。

The pop3 protocol is an email protocol to download messages from the email-server. These messages can be stored in the local machine.

Key Points

Key Points

  1. POP is an application layer internet standard protocol.

  2. Since POP supports offline access to the messages, thus requires less internet usage time.

  3. POP does not allow search facility.

  4. In order to access the messaged, it is necessary to download them.

  5. It allows only one mailbox to be created on server.

  6. It is not suitable for accessing non mail data.

  7. POP commands are generally abbreviated into codes of three or four letters. Eg. STAT.

POP Commands

下表描述了一些 POP 命令:

The following table describes some of the POP commands:

S.N.

Command Description

1

LOGIN This command opens the connection.

2

STAT It is used to display number of messages currently in the mailbox.

3

LIST It is used to get the summary of messages where each message summary is shown.

4

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

5

DELE It is used to delete a message.

6

RSET It is used to reset the session to its initial state.

7

QUIT It is used to log off the session.

Pyhton 的 poplib 模块提供了名为 pop() 和 pop3_SSL() 的类,用于满足此要求。我们将主机名和端口号作为参数提供。在以下示例中,我们连接到 gmail 服务器并在提供登录凭据后检索邮件。

Pyhton’s poplib module provides classes named pop() and pop3_SSL() which are used to achieve this requirement. We supply the hostname and port number as argument. In the below example we connect to a gmail server and retrieve the messages after supplying the login credentials.

import  poplib

user = 'username'
# Connect to the mail box
Mailbox = poplib.POP3_SSL('pop.googlemail.com', '995')
Mailbox.user(user)
Mailbox.pass_('password')
NumofMessages = len(Mailbox.list()[1])
for i in range(NumofMessages):
    for msg in Mailbox.retr(i+1)[1]:
        print msg
Mailbox.quit()

当运行上述程序时,将检索邮件。

The messages are retrieved when the above program is run.