Python邮件处理

170 阅读3分钟

Python邮件处理

1. 简介

Python 提供了丰富的库和工具来处理电子邮件,从发送简单的文本邮件到解析复杂的多媒体邮件,都可以轻松实现。本文将介绍如何使用 Python 发送和接收邮件,以及处理邮件的常见任务。


2. 发送邮件

2.1 使用 smtplib 发送邮件

Python 的 smtplib 模块用于连接 SMTP(Simple Mail Transfer Protocol)服务器并发送邮件。

示例代码:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
​
def send_email(subject, body, sender, recipient, smtp_server, port, login, password):
    # 创建邮件对象
    msg = MIMEMultipart()
    msg['From'] = sender
    msg['To'] = recipient
    msg['Subject'] = subject
​
    # 添加邮件内容
    msg.attach(MIMEText(body, 'plain'))
​
    # 连接 SMTP 服务器并发送邮件
    with smtplib.SMTP(smtp_server, port) as server:
        server.starttls()  # 启用加密传输
        server.login(login, password)
        server.sendmail(sender, recipient, msg.as_string())
​
# 示例调用
send_email(
    subject="测试邮件",
    body="这是使用 Python 发送的测试邮件。",
    sender="your_email@example.com",
    recipient="recipient@example.com",
    smtp_server="smtp.example.com",
    port=587,
    login="your_email@example.com",
    password="your_password"
)

2.2 发送带附件的邮件

可以通过 MIMEApplication 添加附件。

示例代码:
from email.mime.application import MIMEApplication
​
def send_email_with_attachment(subject, body, sender, recipient, smtp_server, port, login, password, file_path):
    # 创建邮件对象
    msg = MIMEMultipart()
    msg['From'] = sender
    msg['To'] = recipient
    msg['Subject'] = subject
​
    # 添加邮件内容
    msg.attach(MIMEText(body, 'plain'))
​
    # 添加附件
    with open(file_path, 'rb') as f:
        part = MIMEApplication(f.read(), Name=file_path)
        part['Content-Disposition'] = f'attachment; filename="{file_path}"''
        msg.attach(part)
​
    # 连接 SMTP 服务器并发送邮件
    with smtplib.SMTP(smtp_server, port) as server:
        server.starttls()
        server.login(login, password)
        server.sendmail(sender, recipient, msg.as_string())
​
# 示例调用
send_email_with_attachment(
    subject="测试邮件",
    body="请查收附件。",
    sender="your_email@example.com",
    recipient="recipient@example.com",
    smtp_server="smtp.example.com",
    port=587,
    login="your_email@example.com",
    password="your_password",
    file_path="test_file.txt"
)

3. 接收和解析邮件

Python 的 imaplibemail 模块可以用来接收和解析邮件。

3.1 使用 imaplib 连接邮箱

示例代码:
import imaplib
​
def connect_to_mailbox(imap_server, email, password):
    mail = imaplib.IMAP4_SSL(imap_server)
    mail.login(email, password)
    return mail
​
# 示例调用
mail = connect_to_mailbox("imap.example.com", "your_email@example.com", "your_password")
mail.select('inbox')  # 选择收件箱

3.2 读取邮件

可以使用 imaplib 检索邮件,配合 email 模块解析邮件内容。

示例代码:
from email import message_from_bytes
​
def fetch_emails(mail):
    status, messages = mail.search(None, 'ALL')
    email_ids = messages[0].split()
​
    for email_id in email_ids:
        # 获取邮件数据
        status, msg_data = mail.fetch(email_id, '(RFC822)')
        for response_part in msg_data:
            if isinstance(response_part, tuple):
                msg = message_from_bytes(response_part[1])
​
                # 输出邮件基本信息
                print("From:", msg['From'])
                print("Subject:", msg['Subject'])
                print("Body:", msg.get_payload(decode=True).decode())
​
# 示例调用
fetch_emails(mail)

4. 常见问题及解决方案

4.1 登录失败

  • 检查用户名和密码是否正确。
  • 如果使用 Gmail 等邮箱,可能需要开启“允许不安全应用”或创建应用专用密码。

4.2 收发邮件超时

  • 确保 SMTP 和 IMAP 服务器地址及端口正确。
  • 检查网络连接。

4.3 邮件内容乱码

  • 确保邮件内容的编码设置正确,使用 utf-8 编码可以避免大多数乱码问题。

5. 总结

本文介绍了 Python 中如何发送和接收邮件,包括发送带附件的邮件和解析收件箱邮件的内容。通过 smtplibimaplib 的结合,可以实现邮件的完整处理。根据实际需求,可以扩展功能,例如添加 HTML 邮件支持或处理多媒体附件。