Python 提供了对 POP 和 IMAP 协议的支持
一、使用 Python 代码与 POP3 和 IMAP4 邮件服务器进行通信
Python 提供了对 POP 和 IMAP 协议的支持,主要通过标准库中的 poplib
和 imaplib
模块来实现。这些模块允许你使用 Python 代码与 POP3 和 IMAP4 邮件服务器进行通信。
使用 poplib
进行 POP3 操作
poplib
模块用于与 POP3 服务器进行交互。以下是一个示例,展示如何使用 poplib
从邮件服务器获取邮件。
示例:使用 poplib
获取邮件
import poplib
from email import parser
# 连接到POP3服务器
pop3_server = 'pop.example.com'
pop3_user = 'your_email@example.com'
pop3_password = 'your_password'
server = poplib.POP3_SSL(pop3_server)
server.user(pop3_user)
server.pass_(pop3_password)
# 获取邮件统计信息
num_messages = len(server.list()[1])
# 获取并解析最新的一封邮件
if num_messages > 0:
response, lines, octets = server.retr(num_messages)
msg_content = b'\r\n'.join(lines).decode('utf-8')
msg = parser.Parser().parsestr(msg_content)
print('Subject:', msg['subject'])
print('From:', msg['from'])
print('To:', msg['to'])
print('Date:', msg['date'])
print('Body:', msg.get_payload())
# 断开连接
server.quit()
使用 imaplib
进行 IMAP 操作
imaplib
模块用于与 IMAP 服务器进行交互。以下是一个示例,展示如何使用 imaplib
从邮件服务器获取邮件。
示例:使用 imaplib
获取邮件
import imaplib
import email
from email.header import decode_header
# 连接到IMAP服务器
imap_server = 'imap.example.com'
imap_user = 'your_email@example.com'
imap_password = 'your_password'
mail = imaplib.IMAP4_SSL(imap_server)
mail.login(imap_user, imap_password)
# 选择邮箱
mail.select("inbox")
# 搜索邮件
status, messages = mail.search(None, 'ALL')
mail_ids = messages[0].split()
# 获取最新的一封邮件
if mail_ids:
latest_email_id = mail_ids[-1]
status, msg_data = mail.fetch(latest_email_id, '(RFC822)'