python使用qq邮箱发送邮件

要想通过QQ邮箱来发送邮件,需要开启QQ邮箱的设置-账户里POP3/SMTP服务,接下来会通过发送短信验证来获得授权码,有了授权码后就可以在代码里添加了


image.png
import smtplib
from email.mime.text import MIMEText
#封装成类可以从其他模块直接调用
class send_msg(object):
    def __init__(self):
        self.msg_from = '[email protected]'  # 发送方邮箱
        self.passwd = 'lwdlrfojhblofijj'  # 填入发送方邮箱的授权码
        self.msg_to = '[email protected]'  # 收件人邮箱

    def set_title(self,title):
        self.title=title

    def set_body(self,body):
        self.body=body

    def send(self):
        try:
            msg = MIMEText(self.body)
            msg['Subject'] = self.title
            msg['From'] = self.msg_from
            msg['To'] = self.msg_to
            s = smtplib.SMTP_SSL("smtp.qq.com", 465)  # 邮件服务器及端口号
            s.login(self.msg_from, self.passwd)
            s.sendmail(self.msg_from, self.msg_to, msg.as_string())
            print("发送成功")
        except s.SMTPException:
            print("发送失败")
        finally:
            s.quit()


if __name__ =='__main__':
    mail_title = 'my title'
    mail_body = 'my body'
    mail_obj = send_msg()
    mail_obj.set_title(mail_title)
    mail_obj.set_body(mail_body)
    mail_obj.send()

控制台打印出“发送成功”,查看接收邮箱收到该邮件

你可能感兴趣的:(python使用qq邮箱发送邮件)