赞
踩
目录
本文将介绍python程序使用QQ邮箱账号,实现发送邮件的功能。您可以访问我的主页查看更多文章。
(1)通过浏览器登录网页版QQ邮箱,然后进入到设置页面:
(2) 向下滑,找到POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务,开启服务,我的已开启,这边不再做演示,点击管理服务,进入管理界面:
(3)点击生成授权码,然后按照提示操作:
(4)复制保存生成的授权码:
编写sendemail.py:
- import smtplib
- from email.mime.text import MIMEText
- from email.header import Header
-
- class SendEmail():
- def __init__(self, subject, info):
- # 发件人邮箱
- self.sender = '******@qq.com'
- # 发件人邮箱密码(注意不是QQ密码,是授权码)
- self.password = '*********'
- # 收件人邮箱,可以是多个邮箱,使用列表存储
- self.receiver = ['****@qq.com']
- # 发件人昵称
- self.nickname = '***'
-
- # SSL协议端口号要使用465
- self.smtp_ssl_server = 'smtp.qq.com'
- self.smtp_ssl_port = 465
-
- self.subject = subject
- self.info = info
-
- def send_email(self):
-
- message = MIMEText(self.info, 'plain', 'utf-8') # 邮件正文
- message['From'] = Header(f'{self.nickname} <{self.sender}>') # 发件人昵称
- message['To'] = Header(self.receiver[0]) # 收件人昵称
- message['Subject'] = Header(self.subject, 'utf-8') # 邮件主题
-
- try:
- # 登录SMTP服务器,发送邮件
- smtpObj = smtplib.SMTP_SSL(self.smtp_ssl_server, self.smtp_ssl_port)
- smtpObj.login(self.sender, self.password)
- smtpObj.sendmail(self.sender, self.receiver, message.as_string())
- print("邮件发送成功")
- except smtplib.SMTPException as e:
- print("邮件发送失败", e)
-
- if __name__ == '__main__':
-
- # 邮件主题
- subject = 'test'
- # 邮件正文
- info = 'test_info'
-
- test = SendEmail(subject, info)
- test.send_email()
运行sendemail.py,可以看到终端输出:
收件人也收到了邮件:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。