Python邮件模块概览

Python提供了多个内置模块用于邮件处理,使开发者能够轻松实现邮件发送、接收和自动化处理功能。这些模块包含在Python标准库中,无需额外安装。

1
smtplib - 邮件发送

smtplib模块定义了SMTP客户端会话对象,用于通过SMTP协议将邮件发送到任何互联网计算机。支持SMTP和ESMTP协议,可以处理TLS/SSL加密连接。

2
email - 邮件内容构建

email模块提供了一系列类和方法用于构建和解析电子邮件消息。支持创建包含文本、HTML、附件等的复杂邮件结构,并能处理MIME格式。

3
imaplib - 邮件接收

imaplib模块实现了基于IMAP4协议的客户端,用于从邮件服务器接收邮件。支持搜索、获取、删除邮件等操作,是构建邮件接收应用的理想选择。

4
poplib - 替代邮件接收方案

poplib模块提供了基于POP3协议的客户端实现。与IMAP不同,POP3通常将邮件下载到本地并从服务器删除,适合简单的邮件接收需求。

使用smtplib和email发送邮件

发送邮件通常涉及两个模块:email用于构建邮件内容,smtplib用于实际发送邮件。

发送文本邮件
发送HTML邮件
发送带附件邮件
发送简单文本邮件
import smtplib
from email.mime.text import MIMEText
from email.header import Header

# 邮件配置
smtp_server = 'smtp.example.com'
smtp_port = 587  # 对于TLS
sender_email = 'your_email@example.com'
password = 'your_password'
receiver_email = 'recipient@example.com'

# 创建邮件内容
subject = 'Python邮件测试'
body = '这是一封来自Python的测试邮件。'

message = MIMEText(body, 'plain', 'utf-8')
message['From'] = Header('发件人名称', 'utf-8')
message['To'] = Header('收件人名称', 'utf-8')
message['Subject'] = Header(subject, 'utf-8')

try:
    # 创建SMTP连接
    server = smtplib.SMTP(smtp_server, smtp_port)
    server.starttls()  # 启用TLS加密
    server.login(sender_email, password)
    
    # 发送邮件
    server.sendmail(sender_email, [receiver_email], message.as_string())
    print("邮件发送成功!")
except Exception as e:
    print(f"发送失败: {e}")
finally:
    server.quit()
发送HTML格式邮件
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# 邮件配置(同上)

# 创建多部分消息
message = MIMEMultipart('alternative')
message['From'] = sender_email
message['To'] = receiver_email
message['Subject'] = 'HTML格式邮件测试'

# 创建文本和HTML版本
text = "您的邮件客户端不支持HTML邮件。"
html = """
<html>
  <body>
    <h1 style="color: #3498db;">HTML邮件测试</h1>
    <p>这是一封<b>HTML格式</b>的测试邮件。</p>
    <p><a href="https://www.example.com">访问我们的网站</a></p>
  </body>
</html>
"""

# 添加两个版本到邮件中
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
message.attach(part1)
message.attach(part2)

# 发送邮件(同上)
发送带附件的邮件
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication

# 邮件配置(同上)

message = MIMEMultipart()
message['From'] = sender_email
message['To'] = receiver_email
message['Subject'] = '带附件的测试邮件'

# 添加邮件正文
body = "请查收附件中的文件。"
message.attach(MIMEText(body, 'plain'))

# 添加附件
file_path = 'report.pdf'
with open(file_path, 'rb') as file:
    part = MIMEApplication(file.read(), Name='report.pdf')
    part['Content-Disposition'] = f'attachment; filename="{file_path}"'
    message.attach(part)

# 发送邮件(同上)

注意: 实际使用中,建议将邮箱密码等敏感信息存储在环境变量中,而不是直接写在代码里。

使用imaplib接收邮件

imaplib模块允许从IMAP服务器接收和操作邮件。

接收并读取邮件示例
import imaplib
import email
from email.header import decode_header

# 邮箱配置
imap_server = 'imap.example.com'
username = 'your_email@example.com'
password = 'your_password'

# 连接到IMAP服务器
mail = imaplib.IMAP4_SSL(imap_server)
mail.login(username, password)

# 选择邮箱(收件箱)
mail.select('inbox')

# 搜索所有未读邮件
status, messages = mail.search(None, 'UNSEEN')
if status != 'OK':
    print("没有找到邮件")
    exit()

# 获取邮件ID列表
messages = messages[0].split()
for mail_id in messages:
    # 获取邮件内容
    status, data = mail.fetch(mail_id, '(RFC822)')
    if status != 'OK':
        print(f"获取邮件 {mail_id} 失败")
        continue
    
    # 解析邮件内容
    msg = email.message_from_bytes(data[0][1])
    
    # 解码主题
    subject, encoding = decode_header(msg['Subject'])[0]
    if isinstance(subject, bytes):
        subject = subject.decode(encoding if encoding else 'utf-8')
    
    # 解码发件人
    From, encoding = decode_header(msg.get('From'))[0]
    if isinstance(From, bytes):
        From = From.decode(encoding if encoding else 'utf-8')
    
    print(f"主题: {subject}")
    print(f"发件人: {From}")
    
    # 获取邮件正文
    if msg.is_multipart():
        for part in msg.walk():
            content_type = part.get_content_type()
            content_disposition = str(part.get("Content-Disposition"))
            try:
                body = part.get_payload(decode=True).decode()
            except:
                pass
            
            if content_type == "text/plain" and "attachment" not in content_disposition:
                print(f"正文:\n{body}")
    else:
        content_type = msg.get_content_type()
        body = msg.get_payload(decode=True).decode()
        if content_type == "text/plain":
            print(f"正文:\n{body}")
    
    print("="*50)

# 关闭连接
mail.logout()

邮件处理模块对比

模块 主要用途 协议 特点 适用场景
smtplib 发送邮件 SMTP/ESMTP 支持TLS/SSL加密 邮件发送应用
email 构建/解析邮件 N/A 支持MIME格式、附件 邮件内容处理
imaplib 接收邮件 IMAP4 服务器保留邮件副本 邮件客户端、自动化处理
poplib 接收邮件 POP3 下载到本地并删除服务器副本 简单邮件接收

最佳实践与安全建议

  • 始终使用TLS/SSL加密连接以保护邮件内容
  • 避免在代码中硬编码邮箱密码,使用环境变量或安全配置
  • 处理附件时验证文件类型,防止恶意文件执行
  • 为长时间运行的邮件服务实现重连机制
  • 限制邮件发送频率,避免被标记为垃圾邮件
  • 使用DKIM和SPF记录提高邮件送达率
  • 为HTML邮件提供纯文本备选版本