Created
May 8, 2017 07:23
-
-
Save Everfighting/b41f3f8a5b9350f33332e39df9de1d74 to your computer and use it in GitHub Desktop.
python邮件模块stmp优化版
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 = '[email protected]' | |
tolist = ['[email protected]'] | |
acc = ['[email protected]', ] | |
mail_user = '[email protected]' | |
mail_pass = '' | |
file_path = r'./' | |
# # sendmail | |
send = SendMail(from_mail, tolist, acc, mail_user, mail_pass, ) | |
send.send_mail(file_path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment