python smtplib发送邮件
import smtplib, ssl
from email.header import Header
from email.mime.text import MIMEText
# 发送邮件
sender = 'xxx@xxx.com' # 发送邮件的人
receivers = ['xxx@xxx.com'] # 接收邮件人
# 第三方SMTP服务
mailHost = 'smtp.qq.com' # 设置发送服务器
mailUser = 'xxx@xxx.com' # 登录邮箱名
mailPass = 'xxxxxxxxxxxxx' # 口令(授权码)
# 三个参数:第一个是文本内容,第二个plain设置文本格式,第三个utf-8设置编码
message = MIMEText(html, 'html', 'utf-8')
message['From'] = 'xxx@xxx.com' # 发送者
message['To'] = 'xxx@xxx.cn' # 接收者
subject = 'python发送邮件' # 发送邮件标题
message['Subject'] = Header(subject, 'utf-8')
try:
smtpObj = smtplib.SMTP_SSL(mailHost, 465) # 发送服务器的端口号
smtpObj.connect(mailHost, 465)
smtpObj.ehlo() # 若不加这行,在服务器环境会报错SMTPServerDisconnected("Connection unexpectedly closed")
smtpObj.login(mailUser, mailPass)
smtpObj.sendmail(sender, receivers, message.as_string())
print('邮件发送成功')
except smtplib.SMTPException:
print('邮件发送失败')