要在 CentOS 上实现 定时执行 Python 邮件发送任务,整个流程分为三步:
✅ 步骤 1:准备 Python 邮件脚本
你先创建一个 Python 文件,例如:/opt/send_mail/send_mail.py
示例代码(QQ/企业邮箱/SMTP 均可替换):
import smtplib
from email.mime.text import MIMEText
from email.header import Header
def send_mail():
mail_host = "smtp.qq.com"
mail_user = "你的邮箱@qq.com"
mail_pass = "你的授权码"
sender = mail_user
receivers = ["收件人邮箱@example.com"]
message = MIMEText("这是一封来自 CentOS 的测试邮件", "plain", "utf-8")
message["From"] = Header("服务器定时任务", "utf-8")
message["To"] = Header("用户", "utf-8")
message["Subject"] = Header("CentOS 定时邮件任务", "utf-8")
try:
smtp = smtplib.SMTP_SSL(mail_host, 465)
smtp.login(mail_user, mail_pass)
smtp.sendmail(sender, receivers, message.as_string())
smtp.quit()
print("邮件发送成功")
except Exception as e:
print("邮件发送失败:", e)
if __name__ == "__main__":
send_mail()
📌 注意
- 不能使用邮箱登录密码,需要用 SMTP 授权码
- 465 端口用于 SSL 加密,视邮箱而定
- 目录路径尽量固定,不要放在 Home 里避免权限问题
✅ 步骤 2:测试执行脚本
确保 Python 能正常运行:
python3 /opt/send_mail/send_mail.py
如果提示缺少库:
pip3 install smtplib email --upgrade
(有些 Python 版本自带,无需安装)
✅ 步骤 3:配置 Crontab 定时任务
编辑计划任务:
crontab -e
例如每天上午 9 点发送邮件:
0 9 * * * /usr/bin/python3 /opt/send_mail/send_mail.py >> /opt/send_mail/mail.log 2>&1
✅ 配置说明
| 字段 | 含义 |
|---|---|
| 0 9 * * * | 每天 09:00 执行 |
| /usr/bin/python3 | Python 绝对路径 |
| >> mail.log 2>&1 | 保存日志 & 错误输出 |
查看 Python 路径:
which python3
🔍 Cron 状态检查 / 调试
显示现有计划任务:
crontab -l
查看执行日志:
tail -f /var/log/cron
查看你自己的日志:
tail -f /opt/send_mail/mail.log
✅ 落地效果
✔ 邮件自动发送
✔ 定时执行
✔ 出错自动记录
✔ 可扩展任务内容
如果你愿意,我还可以帮你:
✅ 增加 HTML 邮件、美化模板
✅ 添加附件、图片、PDF
✅ 连接 MySQL,发送业务数据日报
✅ 失败告警 & 重试机制
✅ Docker 容器内运行 + Supervisor 监控任务
好的,阿杰,下面是补充的 参考资料 & 出站链接,你可以用来查阅细节、扩展功能、或者做调试用。建议你把它们收藏起来,作为长期查阅的工具。
📚 推荐参考资料(外部链接)
关于 Python 邮件发送
- 官方
smtplib模块文档(Python 标准库):
https://docs.python.org/3/library/smtplib.html (Python documentation) - 官方
email包文档(构建邮件内容所用):
https://docs.python.org/3/library/email.html (Python documentation) - 实用教程 “Sending Emails With Python” (Real Python):
https://realpython.com/python-send-email/ (Real Python) - “Guide to smtplib” (Mailtrap):
https://mailtrap.io/blog/smtplib/ (Mailtrap)
关于 CentOS / Linux 定时任务(cron)
- DigitalOcean 教程 “How To Use Cron to Automate Tasks on CentOS 8”:
https://www.digitalocean.com/community/tutorials/how-to-use-cron-to-automate-tasks-centos-8 (数字海洋) - “How to Create and Set Up a Cron Job in Linux” (phoenixNAP):
https://phoenixnap.com/kb/set-up-cron-job-linux (phoenixNAP | Global IT Services) - “Configure Crontab CentOS 7” (Bobcares):
https://bobcares.com/blog/configure-crontab-centos-7/ (Bobcares)
发表回复