前提条件:邮箱开通stmp服务,需要使用授权码登录邮箱
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 第三方 SMTP 服务
mail_host = "smtp.126.com" # 设置服务器
mail_user = "xxx@126.com" # 用户名
mail_pass = "授权码" # 口令
# 设置邮件发送者
sender = 'xxxx@126.com'
# 设置邮件接收者
receivers = ['xxx@xxx.com.cn'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
# 创建一个带附件的实例,发送内容:邮件发送测试...
message = MIMEText('邮件发送测试...', 'plain', 'utf-8')
# 设置发送者
message['From'] = Header("Python脚本", '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) # 25 为 SMTP 端口号
smtpObj.login(mail_user,mail_pass)
smtpObj.sendmail(sender, receivers, message.as_string())
print("邮件发送成功")
except smtplib.SMTPException as e:
line_err = f'error line:{e.__traceback__.tb_lineno}'
print(f"异常行-{line_err} 异常信息:{str(e)}")