使用Python實現批量發送郵件

需求:python

  給定收件人列表,使用指定的發件人給全部收件人逐個發送郵件,並能夠指定郵件內容與附件。服務器

Python代碼:app

#!/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

郵件內容.txtui

測試標題
---------------------------------------------------------------------
XX你好,
    測試內容1
    測試內容2
    測試內容3

                                                 xxx
                                                 2015-11-13
相關文章
相關標籤/搜索