在日常工作中,我们经常需要发送邮件,比如 批量通知、营销推广、日报自动发送、服务器告警提醒等。如果手动发送邮件,不仅繁琐,而且容易出错。而 Python 提供了强大的 smtplibemail 模块,可以实现邮件的自动化发送,无论是纯文本邮件,还是带附件、HTML 格式的邮件,都可以轻松搞定!

本篇博客将介绍如何使用 Python 批量发送邮件、添加附件、发送 HTML 邮件,并结合 schedule 实现定时邮件发送,让你的工作更智能、更高效!🚀


一、SMTP 协议简介

SMTP(Simple Mail Transfer Protocol)是用于发送邮件的协议。常见的邮件服务器及其 SMTP 服务器地址如下:

邮箱提供商

SMTP 服务器

端口

Gmail

 smtp.gmail.com

587

Outlook

 smtp.office365.com

587

QQ 邮箱

 smtp.qq.com

465(SSL)

163 邮箱

 smtp.163.com

465(SSL)

💡 注意:某些邮箱需要开启 SMTP 服务 并生成授权码(例如 QQ 邮箱、163 邮箱)。


二、Python 发送纯文本邮件

首先,我们使用 smtplibemail 发送一封 最简单的文本邮件

1. 安装必要的库

Python 内置 smtplibemail 模块,无需额外安装。

2. 发送邮件的基本代码
import smtplib
from email.mime.text import MIMEText

# 发送者邮箱和密码(使用授权码)
sender_email = "your_email@example.com"
password = "your_password"
receiver_email = "recipient@example.com"

# 邮件内容
subject = "Python 自动化邮件测试"
body = "你好!这是 Python 发送的自动化邮件,祝你一天愉快!😊"

# 创建邮件对象
msg = MIMEText(body, "plain", "utf-8")
msg["Subject"] = subject
msg["From"] = sender_email
msg["To"] = receiver_email

# 连接 SMTP 服务器
with smtplib.SMTP("smtp.example.com", 587) as server:
    server.starttls()  # 启用 TLS 加密
    server.login(sender_email, password)  # 登录邮箱
    server.sendmail(sender_email, receiver_email, msg.as_string())  # 发送邮件

print("邮件发送成功!")
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
3. 代码解析:
  • MIMEText(body, "plain", "utf-8"):创建纯文本邮件
  • smtplib.SMTP("smtp.example.com", 587):连接 SMTP 服务器
  • server.starttls():启用加密
  • server.login(sender_email, password):登录邮箱
  • server.sendmail():发送邮件

运行后,邮件就会自动发送到目标邮箱!


三、Python 发送带附件的邮件

如果我们需要发送 带附件的邮件(如 PDF、Excel、图片等),可以使用 MIMEMultipart 组合邮件内容。

1. 发送带附件的邮件
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

# 发送者和接收者
sender_email = "your_email@example.com"
receiver_email = "recipient@example.com"
password = "your_password"

# 创建邮件对象
msg = MIMEMultipart()
msg["From"] = sender_email
msg["To"] = receiver_email
msg["Subject"] = "Python 发送带附件的邮件"

# 添加邮件正文
body = "请查收附件,内含重要文件。"
msg.attach(MIMEText(body, "plain"))

# 添加附件
file_path = "example.pdf"
with open(file_path, "rb") as attachment:
    part = MIMEBase("application", "octet-stream")
    part.set_payload(attachment.read())

encoders.encode_base64(part)
part.add_header("Content-Disposition", f"attachment; filename={file_path}")

msg.attach(part)

# 连接 SMTP 服务器并发送邮件
with smtplib.SMTP("smtp.example.com", 587) as server:
    server.starttls()
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, msg.as_string())

print("邮件发送成功,附件已附带!")
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
2. 代码解析:
  • MIMEMultipart():创建邮件对象,可包含多个部分(正文 + 附件)
  • MIMEBase("application", "octet-stream"):创建附件对象
  • encoders.encode_base64(part):对附件进行 Base64 编码
  • part.add_header("Content-Disposition", "attachment"):设置附件名称

运行后,邮件会携带附件发送到目标邮箱!


四、Python 发送 HTML 邮件(带图片、超链接)

如果我们需要发送 美观的 HTML 格式邮件,比如:

  • 带超链接
  • 嵌入图片
  • 自定义 HTML 样式

可以使用 MIMEText 创建 HTML 格式邮件:

import smtplib
from email.mime.text import MIMEText

# 发送者信息
sender_email = "your_email@example.com"
receiver_email = "recipient@example.com"
password = "your_password"

# HTML 邮件内容
html_content = """
<html>
<head>
    <style>
        .title {color: blue; font-size: 20px;}
        .content {color: green;}
    </style>
</head>
<body>
    <h2 class='title'>Python 自动化邮件</h2>
    <p class='content'>你好,这是一个 <strong>HTML 格式</strong> 的自动化邮件。</p>
    <p>点击 <a href="https://www.python.org">这里</a> 访问 Python 官网。</p>
    <img src="https://www.python.org/static/community_logos/python-logo.png" width="150">
</body>
</html>
"""

# 创建邮件对象
msg = MIMEText(html_content, "html", "utf-8")
msg["Subject"] = "Python HTML 邮件测试"
msg["From"] = sender_email
msg["To"] = receiver_email

# 发送邮件
with smtplib.SMTP("smtp.example.com", 587) as server:
    server.starttls()
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, msg.as_string())

print("HTML 邮件发送成功!")
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.

邮件示例: 📧 Python 自动化邮件

  • 🔗 带超链接
  • 🖼 嵌入图片
  • 🎨 HTML 样式美化

五、定时发送邮件(schedule)

如果你需要 每天自动发送邮件,可以使用 schedule 库。

1. 安装 schedule
pip install schedule
  • 1.
2. 设置定时任务,每天 9:00 发送邮件
import schedule
import time

def send_email():
    print("正在发送邮件...")
    # 这里调用邮件发送函数

# 设定每天 9:00 发送
schedule.every().day.at("09:00").do(send_email)

while True:
    schedule.run_pending()
    time.sleep(60)  # 每分钟检查一次任务
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.

运行后,邮件会自动在每天 9:00 发送,无需手动操作!


六、总结

在本篇博客中,我们学习了 如何使用 Python 进行邮件自动化,包括:

发送纯文本邮件(smtplib)
发送带附件的邮件(PDF、Excel、图片)
发送 HTML 格式邮件(带超链接、图片)
定时发送邮件(schedule)

📌 掌握这些技巧,你可以用 Python 轻松完成邮件自动化,提高办公效率! 🚀

希望本篇博客对你有帮助!💡 🎯