import smtplib
import pandas as pd
import time
import datetime
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.image import MIMEImage
import os

def send_mail():
# 发送邮箱用户名密码
user = '85755xxxx@qq.com'
# 授权的密码, 并不是qq密码
password = "rijntfojxfdqbbic"
# qq服务器邮箱
sender = "stmp.qq.com"

# 接收的邮箱
receive = "wng_xxx@126.com"

# 发送邮件主题和内容
subject = "电商平台"+"(" + time.strftime("%Y-%m-%d", time.localtime()) + ")"+"日报"
msg = MIMEMultipart()
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = user



# 添加邮件中的html
with open('./image/日报格式.html', 'r', encoding='utf8') as f:
content = f.read().replace("xxxx年xx月xx日", time.strftime("%Y-%m-%d", time.localtime()))
# 设置html格式参数
html_part = MIMEText(content, 'html', 'utf-8')
msg.attach(html_part)


# 添加html中的嵌套的图片
# 特别注意: pic_name 必须和html中的src 和 alt中的一致才可以
pic_names = [name for name in os.listdir("./image") if name.endswith(".png")]
for pic_name in pic_names:
fp = open('./image/'+pic_name, 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', pic_name) # 这个id用于上面html获取图片
msg.attach(msgImage)

# 添加附件
send_file1 = open(r"./data/test.xlsx", "rb").read()
att1 = MIMEText(send_file1, "base64", 'utf-8')
att1['Content-Type'] = 'application/octet-stream'
att1['Content-Disposition'] = 'attachment;filename="test.xlsx"'
msg.attach(att1)

smtp = smtplib.SMTP_SSL('smtp.qq.com', 465)
try:
# 收件人和抄送人 如果如果不写, 会在下面sendmail()函数中直接全部当做收件人
# msg["To"] = receive # 可以是多人,逗号分割即可
msg["To"] = "157xx1@163.com,157xx2@163.com"
msg["Cc"] = "157yy3@163.com,157yy4@163.com"
smtp.login(user, password)
smtp.sendmail(user, receive.split(',') + ["15735659041@163.com"], msg.as_string())

smtp.quit()
message1 = "邮件发送成功 " + time.strftime("%Y-%m-%d", time.localtime())
print(message1)
except smtplib.SMTPException as e:
print("Error: 无法发送邮件")
print(e)

send_mail()