使用Python实现批量发送邮件

需求:

  给定收件人列表,使用指定的发件人给所有收件人逐个发送邮件,并可以指定邮件内容与附件。

Python代码:

#!/usr/bin/env python3  
#coding: utf-8
import os
import sys
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.base import MIMEBase
from email import encoders
  
#发送服务器配置
sender_host = 'smtp.163.com:25'
sender_user = 'xxx@163.com'
sender_pwd = 'xxx'
sender_name = 'xxx@163.com'
attach_file = '附件.pdf'

#加载邮件内容:第一行是邮件标题, 第二行是分割线, 第三行之后是邮件正文
default_title = ''
mail_content = ''
if not os.path.exists("邮件内容.txt"):
    print("文件 邮件内容.txt 不存在");
    exit(0);
contentFile = open("邮件内容.txt");
contentLines = contentFile.readlines();
contentFile.close();
if len(contentLines) < 3:
    print("文件 邮件内容.txt 至少三行");
    exit(0);
default_title = contentLines[0];
mail_content = ''.join(contentLines[2:]);

#加载收件人列表
if not os.path.exists("收件人列表.txt"):
    print("文件 收件人列表.txt 不存在");
    exit(0);
recvFile = open("收件人列表.txt");
recvLines = recvFile.readlines();
recvFile.close();

#添加附件
att = MIMEBase('application', 'octet-stream')  
att.set_payload(open(attach_file, 'rb').read())  
att.add_header('Content-Disposition', 'attachment', filename=('gbk', '', attach_file));
encoders.encode_base64(att);

#发送邮件
smtp = smtplib.SMTP();
smtp.connect(sender_host);
smtp.login(sender_user, sender_pwd);
for recv in recvLines:
    msg = MIMEMultipart('alternative');
    msg['Subject'] = default_title;
    msg['From'] = sender_name;
    msg['To'] = recv;
    msg.attach(MIMEText(mail_content));
    msg.attach(att);
    smtp.sendmail(sender_name, recv, msg.as_string());
    print("已发送:" + recv);
smtp.quit();

收件人列表示.txt:

10001@qq.com
10002@qq.com
10003@qq.com

邮件内容.txt

测试标题
---------------------------------------------------------------------
XX你好,
    测试内容1
    测试内容2
    测试内容3

                                                 xxx
                                                 2015-11-13
原文地址:https://www.cnblogs.com/zhuyingchun/p/8932892.html