在上次实现了批量修改文件名后(链接:https://zhuanlan.zhihu.com/p/133727520),又拿来了同事编写的一次性批量发邮件小程序,小编每月向分公司发数据任务算是基本上实现了自动化
需要新建2个.py文件实现,一个auto_email_module.py创建自动发邮件模块,一个auto _send_email.py执行自动发邮件。
auto_email_module.py代码:
from email.utils import parseaddr, formataddr
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
import smtplibclass AutoEmail:def __init__(self):self.from_name = '默认发件人'self.from_mail = ''self.from_password = ''self.to_address = ''self.to_city = ''self.cc_address = ''self.subject = '默认主题'self.body = '%s默认正文'self.enclosure_names = '附件%s.txt'self.enclosure_affirm = '' # 若不添加附件则非空def __set_send(self):smt_set = smtplib.SMTP_SSL('smtp.exmail.qq.com', 465)try:smt_set.login(self.from_mail, self.from_password)except:# print('账号或密码错误。')return '001'from_address = self.__format_address(self.from_name+'<'+self.from_mail)msg = MIMEMultipart()msg['Subject'] = self.subject % self.to_citymsg['From'] = from_addressmsg['Cc'] = self.__format_address(self.cc_address)msg['To'] = self.to_addressmsg.attach(MIMEText(self.body,'plain','utf-8'))if self.enclosure_affirm == '':try:for enclosure in self.enclosure_names.split(';'):try:enclosure_name = enclosure % self.to_cityexcept:enclosure_name = enclosureenclosure = MIMEApplication(open(enclosure_name, 'rb').read())enclosure.add_header('content-disposition', 'attachment', filename=('gbk', '', enclosure_name))msg.attach(enclosure)except:# print('未添加附件或附件设置有误')return '002'smt_set.sendmail(from_address, self.to_address.split(',') + self.cc_address.split(','), msg.as_string())smt_set.quit()def send_email(self, to_addresses):if to_addresses == {}:print('请添加收件人')else:i = 1body = self.bodyfor city_name, addresses in to_addresses.items():self.to_city = city_nametry:self.body = body % self.to_cityexcept:print('邮件正文应包含%s来区分')returnself.to_address = self.__format_address(addresses)print('正在发送第%d封邮件,发向%s' % (i,self.to_city))key = self.__set_send()if key == '001':print('账号或密码错误。')breakelif key == '002':print('未添加附件或附件设置有误')breakelse:print('发送成功')i += 1def __format_address(self, addr):addresses_str = ''for address in addr.split(';'):name, addr = parseaddr(address)if addresses_str == '':addresses_str = formataddr((Header(name, 'utf-8').encode(), addr))else:addresses_str = ','.join((formataddr((Header(name, 'utf-8').encode(), addr)), addresses_str))return addresses_str
auto _send_email.py 代码:
from auto_email_module import AutoEmailreceivers_dic = {'成都': '收件人A邮箱','绵阳': '收件人B邮箱','南京': '收件人C邮箱'
}a = AutoEmail()
a.from_name = '发件人' a.from_mail = '发件人邮箱地址' a.from_password = '发件人邮箱密码' a.cc_address = '抄送人邮箱地址 'a.subject = '%s分公司3月数据' # 邮件主题,可不设置。默认显示‘默认主题’a.body = '%s分公司:n' ' 附件为分公司3月份数据,请查收! n' 'n***此邮件由小程序分发***'
# 邮件正文,%s必须,%s代表分公司名称,可不设置,默认显示‘%s默认正文’a.enclosure_names = '%s分公司.xlsx' # 附件名称,默认添加附件发送a.enclosure_affirm = '' # 默认添加附件,若不添加附件则添加‘no’,否则将报错a.send_email(receivers_dic) # 发送邮件
done!