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

如何不使用smtplib及API向用户发送验证短信或邮件?

无需API与smtplib的验证短信/邮件发送方案

邮件发送方案

借助系统原生命令行工具

  • Linux/macOS 环境:利用系统自带的 sendmail 或 mail 命令,通过 Python 的 subprocess 模块调用执行,无需依赖 smtplib 或第三方 API。
    示例代码:

    import subprocess
    
    def send_verification_email(to_email, verification_code):
        subject = "你的验证代码"
        body = f"你的验证码是:{verification_code}"
        # 调用 mail 命令发送邮件
        subprocess.run(
            ["mail", "-s", subject, to_email],
            input=body.encode("utf-8")
        )
    

    注意:需确保系统已配置好本地邮件传输代理(如 Postfix),能够正常转发邮件到目标邮箱服务器。

  • Windows 环境:使用第三方命令行邮件工具 blat(需提前安装),同样通过 subprocess 调用实现:

    import subprocess
    
    def send_verification_email(to_email, verification_code):
        subject = "你的验证代码"
        body = f"你的验证码是:{verification_code}"
        subprocess.run([
            "blat",
            "-to", to_email,
            "-subject", subject,
            "-body", body,
            "-server", "你的SMTP服务器地址"  # 需配置可用的SMTP服务器,但无需依赖smtplib库
        ])
    

短信发送方案

基于GSM模块的串口通信

如果有硬件GSM模块(如SIM800L),可以通过 Python 的 pyserial 库直接与模块通信发送短信,全程无需第三方API:

import serial
import time

def send_verification_sms(phone_number, verification_code):
    # 根据模块实际串口参数配置
    ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
    time.sleep(1)
    
    # 设置短信为文本模式
    ser.write(b'AT+CMGF=1\r\n')
    time.sleep(0.5)
    
    # 指定接收号码
    ser.write(f'AT+CMGS="{phone_number}"\r\n'.encode())
    time.sleep(0.5)
    
    # 发送验证码内容
    ser.write(f'你的验证码是:{verification_code}'.encode())
    # 发送短信结束符(Ctrl+Z)
    ser.write(b'\x1A')
    time.sleep(1)
    
    ser.close()

注意:需确保GSM模块已插入有效SIM卡,且串口权限配置正确(如Linux下需将用户加入dialout组)。

系统原生短信命令(嵌入式Linux场景)

部分搭载蜂窝模块的嵌入式Linux系统会提供 gammu 这类命令行工具,可通过 subprocess 调用发送短信:

import subprocess

def send_verification_sms(phone_number, verification_code):
    subprocess.run([
        "gammu",
        "sendsms",
        "TEXT",
        phone_number,
        "-text", f"你的验证码是:{verification_code}"
    ])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 22:47:32