在QQ邮箱的设置 -> 账户中开启POP3/SMTP服务:
开启成功后记下生成的授权码,这是用于登录第三方客户端的专用密码。
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import os
class QQMailSender:
def __init__(self, src_email, dest_email, auth_code):
self.src_email = src_email
self.dest_email = dest_email
self.auth_code = auth_code
def send(self, subject, content, path=None):
msg = MIMEMultipart()
msg.attach(MIMEText(content))
if path:
att = MIMEText(open(path, 'rb').read(), 'base64', 'utf-8')
# 支持预览并修改附件名
att.add_header('Content-Disposition', 'attachment', filename=os.path.basename(path))
msg.attach(att)
msg['Subject'] = subject
msg['From'] = self.src_email
msg['To'] = self.dest_email
ssl = smtplib.SMTP_SSL("smtp.qq.com", 465)
ssl.login(self.src_email, self.auth_code)
ssl.sendmail(self.src_email, self.dest_email, msg.as_string())
创建实例对象时输入发送方邮箱、接收方邮箱、授权码。
发送时输入主题、内容、附件(可选)。