python邮件发送:普通文本、html、添加附件
# -*- coding: utf-8 -*- # @Time : 2019/9/19 13:46 # @Author : HuangWenjun # @Email : 350920551@qq.com # @File : send_mail.py # @Software: PyCharm from email.mime.multipart import MIMEMultipart from email.header import Header from email.mime.text import MIMEText import smtplib def sendEmail(subject, mail_body, receiver, file_names=list()): """ :param subject: 邮件标题 :param mail_body: 邮件正文,可以是文字,也可以是html格式 :param receiver: 邮件正文 :param file_names: 邮件接收人 :return: """ smtpserver = 'smtp.exmail.qq.com' #smtp设置 username = 'xxx' #用户登陆账号 password = 'xxx' #用户登陆密码 msg = MIMEMultipart() #邮件正文 msg.attach(MIMEText(mail_body, 'plain', 'utf-8')) msg['Subject'] = Header(subject, 'utf-8') msg['From'] = username msg['To'] = receiver #附件:附件名称用英文 for file_name in file_names: att = MIMEText(open(file_name, 'rb').read(), 'base64', 'utf-8') att["Content-Type"] = 'application/octet-stream' att['Content-Disposition'] = 'attachment;filename="%s"' % (file_name) msg.attach(att) # 登录并发送邮件 try: smtp = smtplib.SMTP() smtp.connect(smtpserver) smtp.login(username, password) smtp.sendmail(sender, receiver.split(','), msg.as_string()) except Exception as e: print(e) print("邮件发送失败!") else: print("邮件发送成功!") finally: smtp.quit() if __name__ == '__main__': subject="测试标题" mail_body="测试本文" receiver="邮箱1,邮箱2" #接收人邮件地址 用逗号分隔 file_names=['文件名称'] sendEmail(subject, mail_body, receiver,file_names)