python 发送邮件

来源:互联网 发布:土巴兔怎么样 知乎 编辑:程序博客网 时间:2024/06/08 11:54
import smtplibfrom email.mime.text import MIMETextfrom email.header import Header# 第三方 SMTP 服务mail_host="smtp.qq.com"  #设置服务器mail_user="is_my_email@qq.com"    #用户名mail_pass="###"   #口令sender ="###@qq.com"receivers ="###@qq.com"message= MIMEText('测试邮件','plain','utf-8')subject = 'Python SMTP 邮件测试'message['Subject'] = Header(subject, 'utf-8')message['From'] = sendermessage['To'] = receiverstry:    smtpObj = smtplib.SMTP()    smtpObj = smtplib.SMTP_SSL(mail_host, 465)    #smtpObj.connect(mail_host, 25)  # 25  SMTP 端口号    smtpObj.login(mail_user, mail_pass)    smtpObj.sendmail(sender, receivers, message.as_string())    smtpObj.quit()    print("邮件发送成功")except smtplib.SMTPException:    print("Error: 无法发送邮件")