需求:
给定收件人列表,使用指定的发件人给所有收件人逐个发送邮件,并可以指定邮件内容与附件。
Python代码:
#!/usr/bin/env python3 #coding: utf-8import osimport sysimport smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.mime.image import MIMEImagefrom email.mime.base import MIMEBasefrom 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.com10002@qq.com10003@qq.com
邮件内容.txt
测试标题---------------------------------------------------------------------XX你好, 测试内容1 测试内容2 测试内容3 xxx 2015-11-13