import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
def sendEmail(title, text, send, to, passwd, smtp_server, file):
'''
發送帶附件的郵件
:param title: 郵件標題
:param text: 郵件正文
:param send: 發送者郵箱
:param passwd: 授權碼
:param to: 接收者郵箱
:param smtp_server: 發送郵件的服務器
:param file: 需要發送的附件
:return:
'''
msg = MIMEMultipart()
msg['From'] = send
msg['To'] = to
#文字部分
msg['Subject'] = title # 主題
strstr=text #文字內容
att = MIMEText(strstr,'plain','utf-8')
msg.attach(att)
#附件
att = MIMEApplication(open(file,'rb').read()) #你要發送的附件地址
att.add_header('Content-Disposition', 'attachment', filename=file) #filename可隨意取名
msg.attach(att)
server = smtplib.SMTP()
server.connect(smtp_server) #連接smtp郵件服務器
server.login(send,passwd) #登錄smtp郵件服務器
server.sendmail(send, to, msg.as_string()) #發送
server.close() #關閉
if __name__ == '__main__':
smtp_server = 'smtp.qq.com' # 使用QQ郵箱的SMTP服務器,可切換
from_mail = '*****@qq.com'
mail_pass = '*****'
to_mail = '******@qq.com'
title = 'test'
text = 'send test'
file = 'report_2020-04-08-11-02-30.html'
sendEmail(title=title, text=text, send=from_mail, to=to_mail, passwd=mail_pass, smtp_server=smtp_server, file=file)