用 Python 发邮件与消息通知:SMTP 实战
脚本跑完自动发邮件报告结果。含 163/QQ/企业邮箱的配置差异,以及被拒收的三个原因。
脚本跑完没人知道结果,等于白跑。加一个通知,才算闭环。
基础发信
import smtplib
from email.mime.text import MIMEText
from email.header import Header
def send_mail(subject, body, to_addr,
host="smtp.163.com", port=465,
user="your@163.com", password="授权码"):
msg = MIMEText(body, "plain", "utf-8")
msg["Subject"] = Header(subject, "utf-8")
msg["From"] = user
msg["To"] = to_addr
with smtplib.SMTP_SSL(host, port, timeout=15) as s:
s.login(user, password)
s.sendmail(user, [to_addr], msg.as_string())
注意 password 填的是授权码,不是登录密码。所有主流邮箱现在都要求用授权码。
各邮箱配置
| 邮箱 | SMTP 服务器 | 端口 | 备注 |
|---|---|---|---|
| 163 | smtp.163.com | 465 (SSL) | 需在设置里开 SMTP,拿授权码 |
| smtp.qq.com | 465 (SSL) | 同上 | |
| 腾讯企业邮 | smtp.exmail.qq.com | 465 (SSL) | 用邮箱密码或客户端专用密码 |
| Gmail | smtp.gmail.com | 587 (STARTTLS) | 需开两步验证 + 应用专用密码 |
| Outlook | smtp.office365.com | 587 (STARTTLS) | 基本认证已停用,要用 OAuth |
Gmail 和 Outlook 走 587 端口,要用 SMTP + starttls():
with smtplib.SMTP("smtp.gmail.com", 587, timeout=15) as s:
s.starttls()
s.login(user, password)
s.sendmail(user, [to], msg.as_string())
发 HTML 邮件
html = ("<h2>备份完成</h2>"
"<table border='1' cellpadding='6' style='border-collapse:collapse'>"
"<tr><th>项目</th><th>结果</th></tr>"
"<tr><td>文件数</td><td>128</td></tr>"
"<tr><td>耗时</td><td>42 秒</td></tr>"
"</table>")
msg = MIMEText(html, "html", "utf-8")
纯文本和 HTML 都发(客户端会自动选):
from email.mime.multipart import MIMEMultipart
msg = MIMEMultipart("alternative")
msg.attach(MIMEText("备份完成,共 128 个文件", "plain", "utf-8"))
msg.attach(MIMEText(html, "html", "utf-8"))
带附件
from email.mime.application import MIMEApplication
with open("report.xlsx", "rb") as f:
part = MIMEApplication(f.read())
part.add_header("Content-Disposition", "attachment", filename="report.xlsx")
msg.attach(part)
邮件被拒收的三个原因
1. 被判定为垃圾邮件
主题别写「免费」「中奖」「紧急」,正文别全是链接。发给自己测试时也一样——很多邮箱对「自己发给自己」反而更敏感。
2. 频率太高
免费邮箱有发信限额。163 大约每天 50 封,QQ 类似。超了会临时封禁。
如果脚本每天发多封,用企业邮箱或专门的发信服务(SendGrid、阿里云邮件推送)。
3. 缺少 SPF/DKIM
用自己域名发信,没有配 SPF 记录,收件方大概率扔进垃圾箱。
DNS 加一条 TXT:
v=spf1 include:spf.mail.qq.com ~all
具体值看邮箱服务商文档。
更轻的通知方式
很多时候不需要邮件,用这些更直接:
企业微信机器人
import requests
def wecom_notify(webhook, text):
requests.post(webhook, json={
"msgtype": "text",
"text": {"content": text}
}, timeout=10)
wecom_notify("https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx",
"备份完成,128 个文件")
Telegram
def tg_notify(token, chat_id, text):
requests.post(
f"https://api.telegram.org/bot{token}/sendMessage",
json={"chat_id": chat_id, "text": text}, timeout=10)
钉钉
def dingtalk_notify(webhook, text):
requests.post(webhook, json={
"msgtype": "text", "text": {"content": text}
}, timeout=10)
一个完整的通知封装
import logging
def notify(subject, body):
# 发通知,失败只记日志不抛异常
try:
send_mail(subject, body, "me@example.com")
logging.info("通知已发送")
except Exception as e:
logging.error("通知发送失败: %s", e)
关键点:通知失败不能让主流程崩掉。 用 try/except 包住,失败只记日志。
见过太多脚本因为发通知超时,把已经跑完的数据处理结果也一起丢了。
频率控制
定时脚本每天发一封没问题,但如果任务每 10 分钟跑一次,就会变成垃圾邮件轰炸。
加个「只在异常时通知」的开关:
def notify_if_needed(ok, detail):
if not ok:
notify("任务失败", detail)
# 成功时不发,或者每天汇总一次
只在出问题时找你,才是好通知。