邮件自动化

时间:2021-04-07
本文章向大家介绍邮件自动化,主要包括邮件自动化使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

import smtplib
from email.header import Header
from email.utils import formataddr
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import datetime


def eSend():
localtime=datetime.datetime.now().strftime("%Y-%m-%d")
receiver = ['licongcong@kaikeba.com']
sender = 'devaccount@kaikeba.com'
smtpserver = 'smtp.mxhichina.com'
username = sender
password = 'Hk654321'
mail_title = f'主题名称-{localtime}'
# 创建一个带附件的实例
message = MIMEMultipart()
message['From'] = formataddr(["数据组", sender]) # 括号里的对应发件人邮箱昵称、发件人邮箱账号
message['To'] = ",".join(receiver)
message['Subject'] = Header(mail_title, 'utf-8')
# 邮件正文内容
message.attach(MIMEText(f'邮件正文-{localtime},请注意查收', 'plain', 'utf-8'))


#邮件附件(可多个附件)
filepath3 = './各学科汇总.xlsx'
filename3 = f"{datetime.date.today()}附件名称.xlsx"
att3 = MIMEText(open(filepath3, 'rb').read(), 'base64',"utf-8")
att3["Content-Type"] = 'application/octet-stream'
att3.add_header('Content-Disposition', 'attachment', filename=('gbk', '', filename3))
message.attach(att3)

#发送
try:
smtpObj = smtplib.SMTP_SSL(smtpserver, 465) # 注意:如果遇到发送失败的情况(提示远程主机拒接连接),这里要使用SMTP_SSL方法
smtpObj.connect(smtpserver)
smtpObj.login(username, password)
smtpObj.sendmail(sender, receiver, message.as_string())
smtpObj.quit()
print("邮件发送成功!!!")

# 清除文件
# import os
# filelist = [filepath3]
# for i in filelist:
# if os.path.exists(i):
# os.remove(i)
# print(f"文件已删除{i}")
# else:
# print("没有文件可以供删除")

# #另外隔日文件删除
# yesterday = (datetime.datetime.now() + datetime.timedelta(days=-1)).strftime("%Y-%m-%d")
# file3_y = f'./生成数据/{yesterday}分销员明细.xlsx'
# file8_y=f'./生成数据/分销数据表格汇总{yesterday}.xlsx'
# file_list=[file3_y,file8_y]
# for i in file_list:
# if os.path.exists(i):
# os.remove(i)
# print(f'隔日文件已删除{i}')
# else:
# print("没有隔日文件可以删除")
#发送邮件失败
except Exception as e:
print("发送邮件失败")
print(e)
return "ok"




if __name__ == '__main__':
eSend()

原文地址:https://www.cnblogs.com/ccli555/p/14629218.html