from smtplib import SMTP_SSL
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.image import MIMEImage

send_usr = '@qq.com'  # 发件人
send_pwd = '' # 授权码，邮箱设置
reverse = '@qq.com'  # 接收者
content = '2022<p>python官网链接如下：</p>' \
          '<p><a href="https://www.python.org">python</a></p>'
#content 内容设置
html_img = '<p>{content}<br><img src="cid:image1"></br></p>' # html格式添加图片
email_server = 'smtp.qq.com'
email_title = '脚本执行成功了'  # 邮件主题

def send_email1(image_path,email_title):
    msg = MIMEMultipart() # 构建主体
    msg['Subject'] = Header(email_title,'utf-8')  # 邮件主题
    msg['From'] = send_usr  # 发件人
    msg['To'] = Header('xhs','utf-8') # 收件人--这里是昵称
    # msg.attach(MIMEText(content,'html','utf-8'))  # 构建邮件正文,不能多次构造
    # attchment = MIMEApplication(open(r'D:/test.xlsx','rb').read()) # 文件
    # attchment.add_header('Content-Disposition','attachment',filename='test.png')
    # msg.attach(attchment)  # 添加附件到邮件
    # f = open("D:\\PycharmProjects\\cmic_python_JobLog\\xhsmail\\2023-04-30_090212.png", 'rb')  #打开图片
    f = open(image_path, 'rb')  #打开图片
    msgimage = MIMEImage(f.read())
    f.close()
    msgimage.add_header('Content-ID', '<image1>')  # 设置图片
    msg.attach(msgimage)
    msg.attach(MIMEText(html_img,'html','utf-8'))  # 添加到邮件正文
    try:
        smtp = SMTP_SSL(email_server)  #指定邮箱服务器
        smtp.ehlo(email_server)   # 部分邮箱需要
        smtp.login(send_usr,send_pwd)  # 登录邮箱
        smtp.sendmail(send_usr,reverse,msg.as_string())  # 分别是发件人、收件人、格式
        smtp.quit()  # 结束服务
        print('邮件发送完成--')
    except:
        print('发送失败')

# if __name__ == '__main__':
#     send_email1()
