以下是一个基于Python和smtplib模块的简单脚本,可以批量发送邮件。该脚本从一个CSV文件读取收件人列表和邮件内容,然后将邮件发送给每个收件人。
首先需要在代码中填写发送邮件的SMTP服务器地址、用户名和密码,以及邮件的主题和正文。
import smtplib import csv from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication # SMTP服务器地址、用户名和密码 SMTP_SERVER = "smtp.example.com" SMTP_USERNAME = "your_username" SMTP_PASSWORD = "your_password" # 邮件信息 FROM_EMAIL = "sender@example.com" SUBJECT = "邮件主题" BODY = "邮件正文" # 读取收件人列表 with open('recipients.csv') as file: reader = csv.reader(file) recipients = [row[0] for row in reader] # 创建邮件 msg = MIMEMultipart() msg['From'] = FROM_EMAIL msg['Subject'] = SUBJECT msg.attach(MIMEText(BODY)) # 添加附件 filename = "attachment.pdf" with open(filename, "rb") as file: attachment = MIMEApplication(file.read(), _subtype="pdf") attachment.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(attachment) # 发送邮件 with smtplib.SMTP(SMTP_SERVER) as server: server.login(SMTP_USERNAME, SMTP_PASSWORD) for recipient in recipients: msg['To'] = recipient server.sendmail(FROM_EMAIL, recipient, msg.as_string())
注意,在使用该脚本之前,需要确保收件人列表文件recipients.csv已经存在,并且格式为单列的电子邮件地址列表。另外,如果需要发送附件,则需要将附件文件名和路径更新到代码中的相应位置。