本文介绍如何使用 Python 的 smtplib 和 email 库通过 QQ 邮箱发送电子邮件。
pip install secure-smtplib2.获取 QQ 邮箱的 SMTP 授权码。你需要登录到 QQ 邮箱,然后进入设置,找到 SMTP 服务设置,并生成授权码。
import smtplib from email.mime.text import MIMEText from email.header import Header # 堆代码 duidaima.com # QQ 邮箱 SMTP 服务器地址 smtp_server = 'smtp.qq.com' smtp_port = 465 # SSL 端口号 # 发件人和收件人邮箱 sender = 'your_email@qq.com' receiver = 'receiver_email@example.com' # QQ 邮箱 SMTP 授权码 password = 'your_authorization_code' # 邮件内容 subject = 'Hello, this is a test email' content = 'This is a test email sent from Python.' # 创建 MIMEText 对象 msg = MIMEText(content, 'plain', 'utf-8') msg['From'] = Header(sender) msg['To'] = Header(receiver) msg['Subject'] = Header(subject) # 发送邮件 try: server = smtplib.SMTP_SSL(smtp_server, smtp_port) server.login(sender, password) server.sendmail(sender, [receiver], msg.as_string()) print('Email sent successfully.') except Exception as e: print(f'Failed to send email: {e}') finally: server.quit()