如何编写自动化生成并发送邮件

wen 实用脚本 1

本文目录导读:

如何编写自动化生成并发送邮件

  1. Python + SMTP 方式(最常用)
  2. 使用 yagmail 简化版
  3. 批量发送带模板的邮件
  4. 定时发送邮件(使用 schedule 库)
  5. 发送HTML格式化邮件
  6. 使用第三方服务(如SendGrid)
  7. 注意事项

我来介绍几种常用的自动化发送邮件的方法,从简单到复杂:

Python + SMTP 方式(最常用)

基础示例

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os
def send_email(sender_email, sender_password, receiver_email, 
               subject, body, smtp_server, smtp_port, attachments=None):
    """
    发送邮件的通用函数
    """
    try:
        # 创建邮件对象
        message = MIMEMultipart()
        message['From'] = sender_email
        message['To'] = receiver_email
        message['Subject'] = subject
        # 添加邮件正文
        message.attach(MIMEText(body, 'plain', 'utf-8'))
        # 添加附件
        if attachments:
            for file_path in attachments:
                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={os.path.basename(file_path)}'
                    )
                    message.attach(part)
        # 连接到SMTP服务器并发送
        with smtplib.SMTP(smtp_server, smtp_port) as server:
            server.starttls()  # 启用TLS加密
            server.login(sender_email, sender_password)
            server.send_message(message)
        print("邮件发送成功!")
        return True
    except Exception as e:
        print(f"邮件发送失败: {e}")
        return False
# 使用示例
if __name__ == "__main__":
    # 配置信息(以QQ邮箱为例)
    sender = "your_email@qq.com"
    password = "your_smtp_authorization_code"  # 使用授权码,不是QQ密码
    receiver = "receiver@example.com"
    send_email(
        sender_email=sender,
        sender_password=password,
        receiver_email=receiver,
        subject="自动化邮件测试",
        body="这是一封自动发送的测试邮件。",
        smtp_server="smtp.qq.com",
        smtp_port=587,
        attachments=["report.pdf", "data.csv"]  # 可选附件
    )

常用邮箱SMTP配置

EMAIL_CONFIGS = {
    "qq": {
        "smtp_server": "smtp.qq.com",
        "smtp_port": 587,
        "need_ssl": True
    },
    "163": {
        "smtp_server": "smtp.163.com",
        "smtp_port": 25,
        "need_ssl": False
    },
    "gmail": {
        "smtp_server": "smtp.gmail.com",
        "smtp_port": 587,
        "need_ssl": True
    },
    "outlook": {
        "smtp_server": "smtp-mail.outlook.com",
        "smtp_port": 587,
        "need_ssl": True
    }
}

使用 yagmail 简化版

import yagmail
# 更简洁的方式
yag = yagmail.SMTP(
    user='your_email@qq.com',
    password='your_authorization_code',
    host='smtp.qq.com'
)
# 发送邮件
yag.send(
    to=['receiver1@example.com', 'receiver2@example.com'],
    subject='自动化邮件',
    contents=['邮件正文', 'html内容', '附件文件.txt'],
    attachments=['image.jpg', 'document.pdf']
)

批量发送带模板的邮件

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import csv
from string import Template
class EmailAutomation:
    def __init__(self, smtp_config):
        self.smtp_config = smtp_config
        self.server = None
    def connect(self):
        """连接到SMTP服务器"""
        self.server = smtplib.SMTP(
            self.smtp_config['host'],
            self.smtp_config['port']
        )
        self.server.starttls()
        self.server.login(
            self.smtp_config['user'],
            self.smtp_config['password']
        )
    def load_template(self, template_file):
        """加载邮件模板"""
        with open(template_file, 'r', encoding='utf-8') as f:
            return Template(f.read())
    def load_recipients(self, csv_file):
        """从CSV加载收件人列表"""
        recipients = []
        with open(csv_file, 'r', encoding='utf-8') as f:
            reader = csv.DictReader(f)
            for row in reader:
                recipients.append(row)
        return recipients
    def send_bulk_emails(self, template_file, csv_file):
        """批量发送邮件"""
        template = self.load_template(template_file)
        recipients = self.load_recipients(csv_file)
        self.connect()
        for recipient in recipients:
            # 个性化邮件内容
            email_body = template.substitute(recipient)
            msg = MIMEMultipart()
            msg['From'] = self.smtp_config['user']
            msg['To'] = recipient['email']
            msg['Subject'] = f"尊敬的{recipient['name']},您的个性化邮件"
            msg.attach(MIMEText(email_body, 'html', 'utf-8'))
            self.server.send_message(msg)
            print(f"已发送: {recipient['email']}")
        self.server.quit()
        print("全部邮件发送完成!")
# 使用示例
config = {
    'host': 'smtp.qq.com',
    'port': 587,
    'user': 'your_email@qq.com',
    'password': 'your_authorization_code'
}
emailer = EmailAutomation(config)
emailer.send_bulk_emails('template.html', 'recipients.csv')

定时发送邮件(使用 schedule 库)

import schedule
import time
from datetime import datetime
def scheduled_email_job():
    """定时执行的邮件任务"""
    print(f"{datetime.now()}: 开始发送定时邮件...")
    # 这里调用上面的发送函数
    # send_email(...)
    print("定时邮件发送完成")
# 设置定时任务
schedule.every().day.at("09:00").do(scheduled_email_job)  # 每天早上9点
schedule.every().monday.at("10:00").do(scheduled_email_job)  # 每周一10点
schedule.every(30).minutes.do(scheduled_email_job)  # 每30分钟
# 运行定时任务
while True:
    schedule.run_pending()
    time.sleep(1)

发送HTML格式化邮件

def send_html_email(sender, password, receiver, subject, html_content):
    """发送HTML格式邮件"""
    msg = MIMEMultipart('alternative')
    msg['From'] = sender
    msg['To'] = receiver
    msg['Subject'] = subject
    # 纯文本版本(备用)
    text_part = MIMEText("请使用支持HTML的邮件客户端查看", 'plain', 'utf-8')
    msg.attach(text_part)
    # HTML版本
    html_part = MIMEText(html_content, 'html', 'utf-8')
    msg.attach(html_part)
    # 发送...

使用第三方服务(如SendGrid)

from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
def send_via_sendgrid():
    """使用SendGrid发送邮件"""
    message = Mail(
        from_email='sender@example.com',
        to_emails='receiver@example.com',
        subject='SendGrid Test',
        html_content='<strong>测试邮件</strong>'
    )
    sg = SendGridAPIClient('YOUR_SENDGRID_API_KEY')
    response = sg.send(message)
    print(f"发送状态: {response.status_code}")

注意事项

  1. 邮箱授权码:大部分邮箱需要开启SMTP服务并获取授权码,不是直接使用登录密码

  2. 发送限制:免费邮箱通常有每日发送限制(如Gmail每日500封)

  3. 垃圾邮件处理:避免发送大量相同内容,否则可能被标记为垃圾邮件

  4. 安全考虑

    # 不要硬编码密码,使用环境变量
    import os
    password = os.getenv('EMAIL_PASSWORD')
    # 或使用配置文件
    import configparser
    config = configparser.ConfigParser()
    config.read('config.ini')
    password = config['email']['password']

根据需要选择合适的方案,对于简单任务使用基本的SMTP即可,批量任务建议使用封装好的库。

抱歉,评论功能暂时关闭!