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

请求修改Python邮件程序:按指定规则给多收件人发送对应附件

Python邮件发送程序:按指定规则给收件人发送对应PDF附件

没问题,我帮你调整好了这个邮件发送工具,它会严格按照你提供的收件人列表文本文件,给每个用户发送他们专属的PDF附件。下面是完整的实现代码,还有关键部分的说明:

前置准备

  • 确保你的Python环境里有标准库smtplib和email模块(一般Python默认都自带,不需要额外安装)
  • 把收件人列表文件命名为recipients.txt,和PDF文件、程序放在同一个文件夹里
  • 记得替换代码里的邮箱配置信息(发件人邮箱、SMTP服务器、端口、授权密码)

完整代码

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import os

def send_email(smtp_server, smtp_port, sender_email, sender_password, recipient_name, recipient_email, attachments):
    # 创建邮件对象
    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = recipient_email
    msg['Subject'] = f"专属文件送达 - {recipient_name}"

    # 添加邮件正文
    body = f"您好{recipient_name},\n\n这是您需要的文件,请查收附件。\n\n祝好,\n邮件自动发送系统"
    msg.attach(MIMEText(body, 'plain', 'utf-8'))

    # 添加指定的附件
    for pdf_file in attachments:
        pdf_path = os.path.join(os.getcwd(), pdf_file)
        if not os.path.exists(pdf_path):
            print(f"警告:文件 {pdf_file} 不存在,已跳过该附件")
            continue
        with open(pdf_path, 'rb') as f:
            part = MIMEApplication(f.read(), _subtype='pdf')
            part.add_header('Content-Disposition', 'attachment', filename=pdf_file)
            msg.attach(part)

    # 发送邮件
    try:
        with smtplib.SMTP_SSL(smtp_server, smtp_port) as server:
            server.login(sender_email, sender_password)
            server.send_message(msg)
        print(f"成功发送邮件给 {recipient_name} ({recipient_email})")
    except Exception as e:
        print(f"发送邮件给 {recipient_name} ({recipient_email}) 失败:{str(e)}")

def main():
    # 配置邮箱信息,请根据你的邮箱服务商修改
    SMTP_SERVER = 'smtp.qq.com'  # 比如QQ邮箱用这个,Gmail用smtp.gmail.com
    SMTP_PORT = 465
    SENDER_EMAIL = 'your_email@qq.com'
    SENDER_PASSWORD = 'your_authorization_code'  # 注意是授权密码,不是登录密码

    # 读取收件人列表文件
    recipients_file = 'recipients.txt'
    if not os.path.exists(recipients_file):
        print(f"错误:收件人文件 {recipients_file} 不存在")
        return

    with open(recipients_file, 'r', encoding='utf-8') as f:
        lines = f.readlines()

    for line in lines:
        line = line.strip()
        if not line:
            continue  # 跳过空行
        parts = line.split()
        if len(parts) < 2:
            print(f"警告:行内容格式错误,已跳过:{line}")
            continue
        recipient_name = parts[0]
        recipient_email = parts[1]
        attachments = parts[2:]  # 从第三个元素开始都是要发送的PDF文件名
        send_email(SMTP_SERVER, SMTP_PORT, SENDER_EMAIL, SENDER_PASSWORD, recipient_name, recipient_email, attachments)

if __name__ == '__main__':
    main()

关键功能说明

  • 收件人文件解析:程序会逐行读取recipients.txt,每行按空格拆分,第一个元素是姓名,第二个是邮箱,剩下的全部是要发送的PDF文件名
  • 附件校验:发送前会检查PDF文件是否存在,不存在的话会打印警告并跳过,不会影响其他附件的发送
  • 错误处理:无论是邮件发送失败还是文件找不到,都会输出清晰的错误信息,方便你排查问题
  • 中文支持:邮件正文和附件名都用了UTF-8编码,避免中文乱码问题

使用示例

假设你的recipients.txt内容是:

Alice alice@example.com file1.pdf
Bob bob@example.com file2.pdf file1.pdf
Charlie charlie@example.com file3.pdf

程序会给Alice发file1.pdf,给Bob发file2.pdf和file1.pdf,给Charlie发file3.pdf。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:14:21