网站首页 > 精选文章 正文
在 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')
掌握邮件发送后,你可以实现:
自动化报表发送
系统异常报警
批量通知推送
用户注册验证
猜你喜欢
- 2025-06-30 发垃圾邮件最害怕的是什么?(发垃圾邮件违法吗)
- 2025-06-30 快评丨东北学生热得在楼道操场打地铺,学校装空调究竟有多难?
- 2025-06-30 不要信!合肥已有考生上当(合肥报考)
- 2025-06-30 分享一个临时的谷歌邮箱,保护隐私亲测好用
- 2025-06-30 没有一点点防备,QQ突然大更新(为什么qq更新了没有更新功能)
- 2025-06-30 iDRAC9配置邮箱接收报警信息(idrac邮件报警)
- 2025-06-30 邀请国外嘉宾参会?这些关键点你一定不能忽视!
- 2025-06-30 SpringBoot扩展——发送邮件!(springboot 发送post请求)
- 2025-06-30 她点开“期刊网站”被骗走3000!教你如何3秒识别仿冒网站
- 2025-06-30 超大附件不过期,腾讯QQ邮箱“文件中转站”升级为“文件云盘”
- 07-10超惊艳 Vue3.x 组件库Na"ive UI(好词好句人民日报惊艳文词)
- 07-10基于SpringBoot+VUE实现博客系统(vue+springboot项目)
- 07-10使用jenkins一键打包发布vue项目(jenkins vue打包)
- 07-10【推荐】一个基于 FastAPI + Vue3 开发的免费轻量级文件分享工具
- 07-10uniapp搭配vue3开发微信抖音直播实践
- 07-10分享15个基于Vue3.0全家桶的优秀开源项目
- 07-10vue引入微信jssdk(vue 引入 js)
- 07-10基于springboot、tio、oauth2.0前端vuede 超轻量级聊天软件分享
- 最近发表
-
- 超惊艳 Vue3.x 组件库Na"ive UI(好词好句人民日报惊艳文词)
- 基于SpringBoot+VUE实现博客系统(vue+springboot项目)
- 使用jenkins一键打包发布vue项目(jenkins vue打包)
- 【推荐】一个基于 FastAPI + Vue3 开发的免费轻量级文件分享工具
- uniapp搭配vue3开发微信抖音直播实践
- 分享15个基于Vue3.0全家桶的优秀开源项目
- vue引入微信jssdk(vue 引入 js)
- 基于springboot、tio、oauth2.0前端vuede 超轻量级聊天软件分享
- 威克多和尤尼克斯羽毛球拍哪个好(威克多羽毛球拍和尤尼克斯的对比)
- 简单解说思科命令大全(思科基本配置命令)
- 标签列表
-
- 向日葵无法连接服务器 (32)
- git.exe (33)
- vscode更新 (34)
- dev c (33)
- git ignore命令 (32)
- gitlab提交代码步骤 (37)
- java update (36)
- vue debug (34)
- vue blur (32)
- vscode导入vue项目 (33)
- vue chart (32)
- vue cms (32)
- 大雅数据库 (34)
- 技术迭代 (37)
- 同一局域网 (33)
- github拒绝连接 (33)
- vscode php插件 (32)
- vue注释快捷键 (32)
- linux ssr (33)
- 微端服务器 (35)
- 导航猫 (32)
- 获取当前时间年月日 (33)
- stp软件 (33)
- http下载文件 (33)
- linux bt下载 (33)