Python发送qq邮箱
作者:野牛程序员:2023-12-18 18:05:57python阅读 2946
Python发送qq邮箱
使用Python发送QQ邮箱可以通过SMTP协议来实现。以下是一个使用smtplib库的简单示例代码,只需替换掉相应的变量值:
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 邮件服务器地址
mail_host = "smtp.qq.com"
# 邮箱账号
mail_user = "qq_email@qq.com"
# 邮箱密码(授权码)
mail_pass = "qq_app_password"
# 发件人
sender = "qq_email@qq.com"
# 收件人
receiver = "recipient_email@example.com"
# 邮件内容
subject = "邮件主题"
message = "邮件正文"
# 创建一个MIMEText对象,表示邮件内容
msg = MIMEText(message, 'plain', 'utf-8')
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = sender
msg['To'] = receiver
try:
# 连接邮件服务器
smtp_obj = smtplib.SMTP_SSL(mail_host, 465)
# 登录邮箱
smtp_obj.login(mail_user, mail_pass)
# 发送邮件
smtp_obj.sendmail(sender, receiver, msg.as_string())
# 退出连接
smtp_obj.quit()
print("邮件发送成功")
except Exception as e:
print("邮件发送失败:", e)在上述代码中,需要将qq_email@qq.com和qq_app_password替换为QQ邮箱账号和生成的授权码。同时,将recipient_email@example.com替换为接收邮件的邮箱地址。确保在QQ邮箱设置中开启了SMTP服务,并获取了正确的授权码。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

