现在有个需求,需要在后台数据库变化时主动提醒我,自动发邮件是个很好的选择
开启QQ邮箱的SMTP服务
获取授权码
代码如下
完全参考了菜鸟教程的代码,修改参数即可https://www.runoob.com/python3/python3-smtp.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| import smtplib from email.mime.text import MIMEText from email.header import Header
mail_host="smtp.qq.com" mail_user="xinhaojin@qq.com" mail_pass="tj***********j" sender = 'xinhaojin@qq.com' receivers = ['xinhaojin@qq.com'] message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8') message['From'] = Header("菜鸟教程", 'utf-8') message['To'] = Header("测试", 'utf-8') subject = 'Python SMTP 邮件测试' message['Subject'] = Header(subject, 'utf-8') try: smtpObj = smtplib.SMTP() smtpObj.connect(mail_host, 25) smtpObj.login(mail_user,mail_pass) smtpObj.sendmail(sender, receivers, message.as_string()) print ("邮件发送成功") except smtplib.SMTPException as e: print(e) print ("Error: 无法发送邮件")
|