You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python批量发邮件:每20封延迟1小时的代码修正求助

修正Python邮件分批延迟发送的重复问题

问题根源是你没正确控制邮件列表的遍历范围,导致每次循环都从列表开头重复取地址。下面是修正后的完整实现:

核心逻辑

  • 按设定的批量大小(测试用2,正式用20)拆分邮件地址列表,逐批处理
  • 每批发送完成后,按需延迟(测试5秒,正式3600秒)
  • 通过索引步进+切片的方式,确保每批处理的都是未发送过的地址

修正后的代码示例

import smtplib
import time
from email.mime.text import MIMEText
from email.header import Header

# SMTP配置
SMTP_SERVER = 'smtp.example.com'
SMTP_PORT = 587
SMTP_USER = 'your_email@example.com'
SMTP_PASS = 'your_auth_code_or_password'
EMAIL_SUBJECT = '分批发送测试邮件'
EMAIL_CONTENT = '这是一封通过分批延迟逻辑发送的测试邮件'

# 待发送的邮件地址列表
email_recipients = [
    'user1@test.com',
    'user2@test.com',
    'user3@test.com',
    'user4@test.com',
    'user5@test.com'
]

# 分批参数(测试/正式环境可切换)
BATCH_COUNT = 2  # 测试时每批2封,正式改为20
DELAY_TIME = 5   # 测试延迟5秒,正式改为3600秒(1小时)

def send_single_email(to_addr):
    """发送单封邮件的基础函数"""
    msg = MIMEText(EMAIL_CONTENT, 'plain', 'utf-8')
    msg['From'] = Header(SMTP_USER, 'utf-8')
    msg['To'] = Header(to_addr, 'utf-8')
    msg['Subject'] = Header(EMAIL_SUBJECT, 'utf-8')

    try:
        with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as smtp_conn:
            smtp_conn.starttls()
            smtp_conn.login(SMTP_USER, SMTP_PASS)
            smtp_conn.sendmail(SMTP_USER, to_addr, msg.as_string())
        print(f"✅ 邮件发送成功: {to_addr}")
    except Exception as e:
        print(f"❌ 邮件发送失败{to_addr}: {str(e)}")

def batch_send_emails(recipients, batch_size, delay):
    """分批发送邮件,每批后延迟"""
    total_recipients = len(recipients)
    # 按批次步进遍历,确保每批处理未发送地址
    for start_idx in range(0, total_recipients, batch_size):
        current_batch = recipients[start_idx:start_idx + batch_size]
        print(f"\n=== 开始发送第{start_idx//batch_size + 1}批 ({len(current_batch)}封) ===")
        for addr in current_batch:
            send_single_email(addr)
        # 最后一批发送完成后无需延迟
        if start_idx + batch_size < total_recipients:
            print(f"等待{delay}秒后发送下一批...")
            time.sleep(delay)

if __name__ == '__main__':
    batch_send_emails(email_recipients, BATCH_COUNT, DELAY_TIME)

关键修正点

  • 用range(0, total_recipients, batch_size)生成批次起始索引,确保每批处理的是全新的地址段
  • 通过切片recipients[start_idx:start_idx + batch_size]截取当前批次,避免重复遍历原列表
  • 添加判断逻辑:只有非最后一批发送完成后才执行延迟,避免不必要的等待

额外建议

  • 正式环境中,建议将SMTP密码/授权码存入环境变量,不要硬编码
  • 可替换print为日志模块(如logging),方便后续排查问题
  • 提前确认邮件服务商的发送频率限制,避免触发反垃圾机制

内容的提问来源于stack exchange,提问作者Dominik Michalko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 01:45:25