使用python发邮件(qq邮箱)

时间:2023-03-09 16:17:14
使用python发邮件(qq邮箱)

今天打算用QQ邮箱作为示例使用的邮箱,其他邮箱基本操作一样。

第一步:首先获取QQ邮箱授权码

1、进入QQ邮箱首页,点击设置,如图,

使用python发邮件(qq邮箱)

2、然后点击账户

使用python发邮件(qq邮箱)

3、拉到这个地方,开启POP3/SMTP服务服务,按照指示操作获取你的邮箱授权码

使用python发邮件(qq邮箱)

4、这个就是你的授权码,保存下来等会用

使用python发邮件(qq邮箱)

第二步,python代码调用发送QQ邮件

#coding:utf-8
import smtplib
from email.mime.text import MIMEText
from email.header import Header class Mail:
def __init__(self):
# 第三方 SMTP 服务 self.mail_host="smtp.qq.com" #设置服务器:这个是qq邮箱服务器,直接复制就可以
self.mail_pass="xxxxxxx" #刚才我们获取的授权码
self.sender = 'xxxxxx@qq.com' #你的邮箱地址
self.receivers = ['xxxxxxxx@xxx.com'] # 收件人的邮箱地址,可设置为你的QQ邮箱或者其他邮箱,可多个 def send(self): content = '你要发送的邮件内容'
message = MIMEText(content, 'plain', 'utf-8') message['From'] = Header("发件人名字,可*填写", 'utf-8')
message['To'] = Header("收件人名字,可*填写", 'utf-8') subject = 'xxxxx' #发送的主题,可*填写
message['Subject'] = Header(subject, 'utf-8')
try:
smtpObj = smtplib.SMTP_SSL(self.mail_host, 465)
smtpObj.login(self.sender,self.mail_pass)
smtpObj.sendmail(self.sender, self.receivers, message.as_string())
smtpObj.quit()
print('邮件发送成功')
except smtplib.SMTPException as e:
print('邮件发送失败') if __name__ == '__main__':
mail = Mail()
mail.send()

试试运行,发送你的邮件吧~