Python+Flask实现便捷SMTP邮件HTTP在线接口.md
Python+Flask实现便捷SMTP邮件HTTP在线接口.md
from flask import Blueprint, jsonify, request
from api.send_email import send_html_email
email_bp = Blueprint("email_bp", __name__, url_prefix="/api/email")
@email_bp.route("/send", methods=["POST"])
def send_email_api():
data = request.json
result = send_html_email(
subject=data["subject"],
html_content=data["content"],
recipients=data["recipients"],
nickname="Flask通知",
)
return jsonify({"code": 200, "msg": result})import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formataddr
from config.init import SMTP_HOST, SMTP_PORT, SENDER_EMAIL, SENDER_PSW
def send_html_email(
# 邮件主题
subject,
# 邮件内容
html_content,
# 收件人邮箱地址
recipients,
# 发件人昵称
nickname,
# 发送超时
timeout=20,
):
# 创建HTML邮件对象
msg = MIMEText(html_content, "html", "utf-8")
# 修复From头格式(核心修复)
msg["From"] = formataddr((nickname, SENDER_EMAIL))
msg["To"] = Header(",".join(recipients), "utf-8")
msg["Subject"] = Header(subject, "utf-8")
# 建立SMTP连接
try:
server = smtplib.SMTP_SSL(host=SMTP_HOST, port=SMTP_PORT, timeout=timeout)
# 调试
# print("开始连接...")
# server.set_debuglevel(1)
# print("开始登录...")
server.login(user=SENDER_EMAIL, password=SENDER_PSW)
# print("开始发送...")
server.sendmail(
from_addr=SENDER_EMAIL, to_addrs=recipients, msg=msg.as_string()
)
return f"邮件发送成功"
except smtplib.SMTPException as err:
return f"邮件发送失败: {err}"
finally:
server.quit()