python 蟒蛇邮件模块STMP优化版
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 蟒蛇邮件模块STMP优化版相关的知识,希望对你有一定的参考价值。
#!/usr/bin/env python3
"""
email负责构造邮件
smtplib负责发送邮件
"""
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.utils import formatdate
import smtplib
import datetime
import os
now = datetime.datetime.now()
day1 = datetime.timedelta(days=0)
trad = now - day1
str_trad = trad.strftime('%Y-%m-%d')
class SendMail:
""""""
def __init__(self, from_mail, tolist, acc, username, password):
self.From = from_mail # 发件人
self.tolist = ','.join(tolist) # 收件人列表
self.acc = ','.join(acc)
# file_name = r'C:\Users\Administrator\Desktop\temp\ex1.xlsx' # 文件名
self.username = username
self.password = password
def send_mail(self, excel_path):
server = smtplib.SMTP("smtp.exmail.qq.com", 25)
server.starttls()
server.set_debuglevel(0)
server.login(self.username, self.password) # smtp服务器验证
# 构造MIMEMultipart对象做为根容器
main_msg = MIMEMultipart()
# 构造MIMEText对象做为邮件显示内容并附加到根容器
text_msg = MIMEText("附件是%s日的数据, 请查收" % str_trad)
main_msg.attach(text_msg)
# 构造MIMEBase对象做为文件附件内容并附加到根容器
contype = 'application/octet-stream'
maintype, subtype = contype.split('/', 1)
for i in os.listdir(excel_path):
file_name = os.path.join(excel_path, i)
# 构造附件1,传送指定目录下的 excel文件
att1 = MIMEText(open(file_name, 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename="{xls}"'.format(xls=i) # filename 客户端接收到的附件名称
main_msg.attach(att1)
# 设置根容器属性
main_msg['From'] = self.From
main_msg['To'] = self.tolist # 收件人
main_msg['Cc'] = self.acc # 抄送人
main_msg['Subject'] = Header("%s日运营数据..." % str_trad).encode() # 邮件主题
main_msg['Date'] = formatdate() # 发件时间
# 得到格式化后的完整文本
fulltext = main_msg.as_string()
# 用smtp发送邮件
try:
server.sendmail(self.From, self.tolist.split(',') + self.acc.split(','), fulltext)
print('success')
except smtplib.SMTPException as e:
print('error', e)
finally:
server.quit()
if __name__ == '__main__':
from_mail = 'caibinbin@cashsoso.com'
tolist = ['903601682@qq.com']
acc = ['binbeing@126.com', ]
mail_user = 'caibinbin@cashsoso.com'
mail_pass = ''
file_path = r'./'
# # sendmail
send = SendMail(from_mail, tolist, acc, mail_user, mail_pass, )
send.send_mail(file_path)
以上是关于python 蟒蛇邮件模块STMP优化版的主要内容,如果未能解决你的问题,请参考以下文章
python3之模块SMTP协议客户端与email邮件MIME对象