You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyScript中smtplib.SMTP连接Gmail服务器失败问题求助

PyScript嵌入网页发送邮件失败的解决方案

问题原因

  • 浏览器安全策略限制:浏览器禁止前端直接发起SMTP协议的网络请求(非HTTP/HTTPS协议),PyScript运行在浏览器的WebAssembly环境中,受此限制无法直接建立SMTP连接。
  • Pyodide网络实现限制:PyScript依赖的Pyodide runtime基于浏览器fetch API实现网络功能,对SMTP这类非HTTP协议的支持不足。

解决方案:后端代理

无法在前端直接用smtplib发送邮件,需要通过后端接口中转处理。以下是具体实现步骤:

1. 搭建后端邮件发送接口(以Flask为例)

创建Flask服务,接收前端传递的邮件参数,在后端完成SMTP发送逻辑:

from flask import Flask, request, jsonify
import smtplib
from email.mime.text import MIMEText
from flask_cors import CORS
import os

app = Flask(__name__)
CORS(app)  # 允许前端跨域请求

# 用环境变量存储敏感信息,避免硬编码
SENDER_EMAIL = os.getenv("SENDER_EMAIL", "senderEmail@gmail.com")
APP_PASSWORD = os.getenv("APP_PASSWORD", "你的Gmail应用专用密码")

@app.route('/send-email', methods=['POST'])
def send_email():
    try:
        data = request.json
        html_content = data.get('html')
        subject = data.get('subject')
        receiver_email = data.get('receiver')

        # 构造邮件
        mail = MIMEText(html_content, 'html', 'utf-8')
        mail['Subject'] = subject
        mail['From'] = SENDER_EMAIL
        mail['To'] = receiver_email

        # 发送邮件
        with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
            smtp.ehlo()
            smtp.starttls()
            smtp.login(SENDER_EMAIL, APP_PASSWORD)
            send_status = smtp.send_message(mail)
        
        return jsonify({"status": "success", "details": send_status})
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)

2. 前端PyScript调用后端接口

修改前端代码,通过pyfetch向后端发送请求,由后端完成邮件发送:

<html>
  <head>
    <script defer src="https://pyscript.net/latest/pyscript.js"></script>
  </head>
  <body>
    <py-script>
import json
from pyodide.http import pyfetch

async def trigger_email_send():
    # 准备邮件HTML内容
    email_html = '''
    <h1>hello</h1>
    <div>這是 HTML 的內容</div>
    <div style="color:red">紅色的字</div>
    '''
    
    # 构造请求参数
    request_data = {
        "html": email_html,
        "subject": "html 的信",
        "receiver": "recevier@gmail.com"
    }

    # 调用后端接口
    response = await pyfetch(
        url="http://localhost:5000/send-email",
        method="POST",
        headers={"Content-Type": "application/json"},
        body=json.dumps(request_data)
    )

    # 处理并打印结果
    result = await response.json()
    print("邮件发送结果:", result)

# 执行邮件发送逻辑
await trigger_email_send()
    </py-script>
  </body>
</html>

关键注意事项

  • Gmail配置要求:使用Gmail发送邮件必须开启两步验证,然后创建应用专用密码(不能直接使用原账号密码)。
  • 安全规范:生产环境中,绝对不要在前端代码中硬编码敏感信息,所有账号密码需放在后端环境变量中。
  • 生产部署要求:后端需配置HTTPS,避免敏感数据明文传输;同时要严格配置CORS策略,仅允许可信域名发起请求。

内容的提问来源于stack exchange,提问作者tony he

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 23:27:46