1. Python自动收发邮件项目概述
在数字化办公场景中,邮件自动化处理已成为提升工作效率的刚需。通过Python实现邮件自动收发,可以完成批量发送通知、定期收取报表、自动分类归档等重复性工作。我曾为某电商团队部署过自动邮件系统,每天处理3000+订单邮件,人力成本降低70%。
核心功能包括:
- SMTP协议发送带附件的邮件
- IMAP/POP3协议收取并解析邮件
- 基于规则的内容过滤与自动回复
- 邮件内容模板化与个性化定制
典型应用场景:
- 电商订单状态自动通知
- 周报月报定时发送
- 验证码/告警信息自动推送
- 客户服务工单自动响应
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 核心模块与技术选型
2.1 邮件协议对比
| 协议类型 | 端口号 | 加密方式 | Python库 | 适用场景 |
|---|---|---|---|---|
| SMTP | 25/465/587 | SSL/TLS | smtplib | 发送邮件 |
| IMAP4 | 143/993 | STARTTLS/SSL | imaplib | 邮件管理 |
| POP3 | 110/995 | SSL | poplib | 简单收取 |
实际项目中更推荐IMAP协议,因为它支持:
- 服务器端邮件状态同步
- 选择性下载邮件部分内容
- 创建和管理邮件文件夹
2.2 关键Python库详解
smtplib使用要点:
python复制import smtplib
from email.mime.multipart import MIMEMultipart
server = smtplib.SMTP_SSL('smtp.example.com', 465)
server.login('user@example.com', 'password')
msg = MIMEMultipart()
msg['From'] = 'sender@example.com'
msg['To'] = 'receiver@example.com'
msg['Subject'] = '订单确认通知'
# 添加正文和附件...
server.send_message(msg)
imaplib实战技巧:
python复制import imaplib
import email
mail = imaplib.IMAP4_SSL('imap.example.com')
mail.login('user@example.com', 'password')
mail.select('inbox')
# 搜索未读邮件
status, messages = mail.search(None, 'UNSEEN')
for mail_id in messages[0].split():
_, data = mail.fetch(mail_id, '(RFC822)')
raw_email = email.message_from_bytes(data[0][1])
# 解析邮件头和内容...
3. 完整实现方案
3.1 发送带附件的营销邮件
python复制from email.mime.application import MIMEApplication
def send_bulk_emails(recipients):
with open('promotion_template.html', 'r') as f:
html_template = f.read()
for user in recipients:
msg = MIMEMultipart()
msg.attach(MIMEText(html_template.format(
name=user['name'],
coupon=user['coupon_code']
), 'html'))
# 添加PDF附件
with open(f"coupons/{user['id']}.pdf", 'rb') as f:
attach = MIMEApplication(f.read(), _subtype='pdf')
attach.add_header('Content-Disposition', 'attachment',
filename=f"优惠券_{user['name']}.pdf")
msg.attach(attach)
server.sendmail(from_addr, user['email'], msg.as_string())
重要提示:群发邮件需注意频率控制,建议每批次间隔10秒以上,避免被判定为垃圾邮件
3.2 自动分类收件箱
python复制def classify_emails():
mail.select('inbox')
_, messages = mail.search(None, 'ALL')
for num in messages[0].split():
_, data = mail.fetch(num, '(RFC822)')
msg = email.message_from_bytes(data[0][1])
if '订单' in msg['Subject']:
mail.copy(num, 'INBOX.Orders')
elif '投诉' in msg['Subject'].lower():
mail.copy(num, 'INBOX.Complaints')
mail.store(num, '+FLAGS', '\\Deleted')
mail.expunge()
4. 高级应用与性能优化
4.1 邮件内容解析技巧
处理复杂邮件时需要注意:
- 多部分内容(text/plain和text/html)
- 内嵌图片(Content-ID引用)
- 不同编码格式(特别是中文邮件)
python复制def get_email_content(msg):
content = []
for part in msg.walk():
if part.get_content_type() == 'text/plain':
charset = part.get_content_charset() or 'utf-8'
content.append(part.get_payload(decode=True).decode(charset))
elif part.get_content_type() == 'text/html':
# 处理HTML内容...
return '\n'.join(content)
4.2 连接池管理
高频邮件处理建议使用连接池:
python复制from smtplib import SMTP_SSL
from imaplib import IMAP4_SSL
import threading
class ConnectionPool:
def __init__(self, max_connections=5):
self.smtp_pool = []
self.imap_pool = []
self.lock = threading.Lock()
def get_smtp_conn(self):
with self.lock:
if self.smtp_pool:
return self.smtp_pool.pop()
return SMTP_SSL('smtp.example.com', 465)
def release_conn(self, conn):
with self.lock:
if isinstance(conn, SMTP_SSL):
self.smtp_pool.append(conn)
elif isinstance(conn, IMAP4_SSL):
self.imap_pool.append(conn)
5. 安全防护与异常处理
5.1 常见安全措施
- 使用App专用密码而非账户密码
- 敏感信息加密存储(如keyring模块)
- 实施速率限制(如每5分钟最多50封)
- 禁用不安全的协议版本(如SSLv3)
5.2 错误处理模板
python复制import time
from smtplib import SMTPException
def safe_send_email(msg, max_retries=3):
for attempt in range(max_retries):
try:
server.send_message(msg)
return True
except SMTPException as e:
if attempt == max_retries - 1:
log_error(f"邮件发送失败: {str(e)}")
return False
time.sleep(2 ** attempt) # 指数退避
6. 实战案例:订单系统集成
某电商平台的自动化流程:
python复制class OrderEmailSystem:
def __init__(self):
self.templates = {
'order_confirm': load_template('confirm.html'),
'ship_notice': load_template('shipping.html'),
'review_reminder': load_template('review.html')
}
def on_order_created(self, order):
msg = build_email(
to=order['customer_email'],
subject=f"订单确认 #{order['id']}",
html=self.templates['order_confirm'].render(order)
)
schedule_email(msg, delay=0)
def on_order_shipped(self, order):
msg = build_email(
to=order['customer_email'],
subject=f"您的订单已发货 #{order['id']}",
html=self.templates['ship_notice'].render({
**order,
'tracking_url': generate_tracking_link(order)
})
)
schedule_email(msg, delay=0)
经验之谈:实际部署时建议使用Celery等任务队列,避免阻塞主业务流程。我曾遇到因同步发送邮件导致订单接口超时的情况,改为异步处理后系统稳定性显著提升
