python qq邮箱发送邮件

时间:2022-09-24 19:13:50

使用qq发送邮件

 

# coding=utf8
"""
qq邮箱发送邮件
"""
import sys

reload(sys)
sys.setdefaultencoding('utf8')

import smtplib
from email.mime.text import MIMEText


class QQMailClient():
    """使用qq邮箱发送邮件"""

    def __init__(self, msg_from, passwd):
        """
        :param msg_from: 发件人邮箱地址
        :param passwd: 发件人邮箱密码,qq邮箱使用授权码是16个字母,而不是自己的邮箱密码。
        """
        self._msg_from = msg_from
        self._passwd = passwd
        self._smtp = smtplib.SMTP_SSL("smtp.qq.com", 465)
        self.__login()

    def __login(self):
        self._smtp.login(self._msg_from, self._passwd)

    def send_mail(self, msg_to, subject, content):
        """
        发送邮件
        :param msg_to: 收件人邮箱地址
        :param subject :邮件主题
        :param content:邮件内容
        :type msg_to:str
        :type subject:str
        :type content:str
        """
        msg = MIMEText(content, _charset='utf8')
        msg['Subject'] = subject
        msg['From'] = self._msg_from
        msg['To'] = msg_to
        self._smtp.sendmail(self._msg_from, msg_to, msg.as_string())

    def quit(self):
        self._smtp.quit()

    def __del__(self):
        self.quit()


if __name__ == "__main__":
    qq_mail_client = QQMailClient('909686716@qq.com', 'ssoodruxniyfbxxx')
    qq_mail_client.send_mail('m13148804506@163.com', '测试主题1', '测试内容1')
    qq_mail_client.send_mail('m13148804506@163.com', '测试主题2', '测试内容2')