Python发送邮件比较简单,掌握两个自带库 smtplib、email 即可。
使用的时候直接 import 。smtplib 负责发送邮件,email 负责构造邮件(邮件内容,主题,收件人,抄送人等)。
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header server = "smtp.qq.com" sender = "XXXXXXX@qq.com" pwd = "AAAAAAAAA" # 授权码 receivers = "YYYYYY@qq.com" # 接收邮件,可设置为你的QQ邮箱或者其他邮箱 # 创建一个带附件的实例 message = MIMEMultipart() message['From'] = Header("fengxing", 'utf-8') message['To'] = Header("执行报告", 'utf-8') subject = '自动化测试执行报告' message['Subject'] = Header(subject, 'utf-8') # 邮件正文内容 message.attach(MIMEText('最新的测试报告', 'plain', 'utf-8')) # 构造附件1,传送当前目录下的 test_doc.txt 文件 att1 = MIMEText(open('./test_doc.txt', 'rb').read(), 'base64', 'utf-8') att1["Content-Type"] = 'application/octet-stream' # 这里的filename可以任意写,写什么名字,邮件中显示什么名字 att1["Content-Disposition"] = 'attachment; filename="文档"' message.attach(att1) smtpObj = smtplib.SMTP() try: smtpObj.connect(server) smtpObj.login(sender, pwd) smtpObj.ehlo() smtpObj.starttls() smtpObj.sendmail(sender, receivers, message.as_string()) print("邮件发送成功") except smtplib.SMTPException as msg: print("Error: 无法发送邮件") print(msg)