python入门到脱坑经典案例:邮件发送
在 Python 中发送电子邮件是自动化办公和系统监控的常用功能。以下是 5 种邮件发送方法的详细实现,涵盖基础发送、附件添加、HTML 内容等场景:
1. 基础文本邮件(SMTP协议)
import smtplib
from email.mime.text import MIMEText
# 配置信息
sender = 'your_email@example.com'
receiver = 'recipient@example.com'
password = 'your_password' # 或应用专用密码
smtp_server = 'smtp.example.com' # 如smtp.qq.com
# 创建邮件内容
message = MIMEText('这是一封测试邮件正文', 'plain', 'utf-8')
message['From'] = sender
message['To'] = receiver
message['Subject'] = 'Python邮件测试'
# 发送邮件
try:
with smtplib.SMTP_SSL(smtp_server, 465) as server: # SSL加密端口
server.login(sender, password)
server.sendmail(sender, receiver, message.as_string())
print("邮件发送成功!")
except Exception as e:
print(f"发送失败: {e}")
关键点:
- 使用 SMTP_SSL 加密连接(端口通常为465)
- 主流邮箱SMTP服务器:
- QQ邮箱:smtp.qq.com
- 163邮箱:smtp.163.com
- Gmail:smtp.gmail.com
2. 发送HTML格式邮件
from email.mime.multipart import MIMEMultipart
html_content = """
<html>
<body>
<h1 style="color:red;">重要通知</h1>
<p>您的订单已发货!</p>
<a href="https://example.com">点击查看详情</a>
</body>
</html>
"""
msg = MIMEMultipart()
msg.attach(MIMEText(html_content, 'html', 'utf-8'))
msg['Subject'] = 'HTML邮件测试'
# 其余配置同基础版...
3. 添加附件(图片/文件)
from email.mime.application import MIMEApplication
msg = MIMEMultipart()
msg.attach(MIMEText('请查收附件', 'plain'))
# 添加Excel附件
with open('report.xlsx', 'rb') as f:
attach = MIMEApplication(f.read(), _subtype="xlsx")
attach.add_header('Content-Disposition', 'attachment', filename='月度报告.xlsx')
msg.attach(attach)
# 添加图片(嵌入正文)
with open('logo.png', 'rb') as f:
img = MIMEImage(f.read())
img.add_header('Content-ID', '<logo>')
msg.attach(img)
msg.attach(MIMEText('<img src="cid:logo">', 'html')) # HTML引用图片
4. 使用第三方库(yagmail)
简化版操作(需安装:pip install yagmail):
import yagmail
yag = yagmail.SMTP(user='your_email@example.com',
password='your_password',
host='smtp.example.com')
contents = [
'邮件正文内容',
'可多个部分自动拼接',
{'附件': '/path/to/file.pdf'}
]
yag.send(to='recipient@example.com',
subject='主题',
contents=contents)
5. 企业邮箱/Exchange服务(OAuth2认证)
from exchangelib import Credentials, Account
credentials = Credentials('username@company.com', 'password')
account = Account('username@company.com',
credentials=credentials,
autodiscover=True)
# 发送邮件
account.send_mail(
subject='会议通知',
body='明天10点会议室A',
to_recipients=['colleague@company.com']
)
6. 常见问题解决方案
问题1:SMTP认证错误
- 检查是否开启SMTP服务(邮箱设置中)
- 使用应用专用密码(如Gmail需16位密码)
- 尝试降低安全等级(部分邮箱需允许"不太安全的应用")
问题2:附件乱码
filename = ('中文文件.pdf', 'utf-8') # 指定编码
attach.add_header('Content-Disposition', 'attachment', filename=filename)
问题3:发送速度慢
- 复用SMTP连接:
- server = smtplib.SMTP_SSL(...) server.sendmail(...) # 多次发送 server.quit() # 最后关闭
7. 安全建议
- 不要硬编码密码:
import os
password = os.getenv('EMAIL_PASSWORD') # 从环境变量读取
使用加密连接:
- 优先选择 SMTP_SSL(端口465)
- 或 starttls()(端口587):
server = smtplib.SMTP(smtp_server, 587)
server.starttls()
8. 完整案例:错误监控邮件
import traceback
def error_monitor():
try:
# 模拟错误代码
1 / 0
except Exception:
error_msg = traceback.format_exc()
msg = MIMEMultipart()
msg.attach(MIMEText(f"程序报错:\n{error_msg}", 'plain'))
msg['Subject'] = '系统异常警报'
# 添加错误日志附件
with open('error.log', 'w') as f:
f.write(error_msg)
with open('error.log', 'rb') as f:
msg.attach(MIMEText(f.read(), 'base64', 'utf-8'))
# 发送代码...
9. 扩展学习
- 批量发送(邮件合并):
recipients = ['a@test.com', 'b@test.com']
for to in recipients:
yag.send(to=to, subject='个性化主题', contents=f'{to}的专属内容')
定时发送(结合 schedule 库):
import schedule
schedule.every().day.at("09:00").do(send_daily_report)
邮件解析(接收邮件):
import imaplib
mail = imaplib.IMAP4_SSL('imap.example.com')
mail.login(user, password)
mail.select('inbox')
掌握邮件发送后,你可以实现:
自动化报表发送
系统异常报警
批量通知推送
用户注册验证