第三方SMTP服务
这里我们使用QQ的SMTP服务
登录QQ邮箱,并打开设置
切换到账号标签下,找到POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务,开启SMTP服务
按照提示发送短信即可,保存好你的授权码,登录账号要用,而不是用你的QQ密码。
代码编写
以下代码改写自菜鸟教程
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 第三方 SMTP 服务
mail_host = "smtp.qq.com" # 设置服务器
mail_user = "XXXXXX@qq.com" # 你的QQ邮箱
mail_pass = "XXXXXXXX" # 刚才的授权码
sender = '2252767663@qq.com' # 注意和上面的QQ邮箱保持一致,否则会出错
receivers = ['2583913384@qq.com'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
message = MIMEText('this is the first time for me to use SMTP, thank you for your any advice!', 'plain', 'utf-8')
message['From'] = Header("菜鸟教程", 'utf-8')
message['To'] = Header("测试", 'utf-8')
subject = 'good news!'
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:
print(e)
print("Error: 无法发送邮件")
邮件截图