QuickJS 如何发送一封邮件 ?

参阅:bellard.org‌ : QuickJS 如何使用 qjs 执行 js 脚本

在 QuickJS 中发送邮件需要依赖外部库或调用系统命令,因为 QuickJS 本身不包含 SMTP 功能。以下是两种实现方法:

方法 1:调用系统命令(推荐)

使用 QuickJS 的 std 模块调用 curl 命令发送邮件(适用于 Linux/macOS):

javascript 复制代码
// qjs sendmail.js
import * as std from 'std';

// 邮件配置
const smtpServer = 'smtp://smtp.example.com:587';
const username = 'your_email@example.com';
const password = 'your_password';
const from = 'sender@example.com';
const to = 'recipient@example.com';
const subject = 'QuickJS 邮件测试';
const body = '这是一封来自 QuickJS 的测试邮件';
const attachmentPath = '/path/to/attachment.txt';

// 构建 curl 命令
const command = [
  'curl',
  '--url', smtpServer,
  '--user', `${username}:${password}`,
  '--mail-from', from,
  '--mail-rcpt', to,
  '--upload-file', '-',
  '--ssl-reqd'
].join(' ');

// 构建 MIME 邮件内容
const boundary = 'quickjs-boundary';
const mimeMessage = [
  `From: <${from}>`,
  `To: <${to}>`,
  `Subject: ${subject}`,
  `MIME-Version: 1.0`,
  `Content-Type: multipart/mixed; boundary="${boundary}"`,
  '',
  `--${boundary}`,
  'Content-Type: text/plain; charset=utf-8',
  '',
  body,
  '',
  `--${boundary}`,
  `Content-Type: application/octet-stream; name="${attachmentPath.split('/').pop()}"`,
  'Content-Disposition: attachment',
  'Content-Transfer-Encoding: base64',
  '',
  std.loadFile(attachmentPath, 'binary').toString('base64'),
  '',
  `--${boundary}--`
].join('\r\n');

// 执行命令
const proc = std.popen(command, 'w');
proc.puts(mimeMessage);
proc.close();

console.log('邮件发送完成');

运行命令:

bash 复制代码
qjs sendmail.js

方法 2:使用原生模块(需要编译)

需要编写 C 扩展模块并编译进 QuickJS:

  1. 创建 mailer.c
c 复制代码
#include "quickjs.h"
#include <libesmtp.h>

static JSValue sendMail(JSContext *ctx, JSValueConst this_val,
                        int argc, JSValueConst *argv) {
    // 实现 SMTP 邮件发送逻辑
    // 使用 libesmtp 库 (https://libesmtp.github.io/)
    // ...
}

static const JSCFunctionListEntry funcs[] = {
    JS_CFUNC_DEF("send", 1, sendMail),
};

static int mailer_init(JSContext *ctx, JSModuleDef *m) {
    return JS_SetModuleExportList(ctx, m, funcs, countof(funcs));
}

JSModuleDef *js_init_module_mailer(JSContext *ctx, const char *module_name) {
    JSModuleDef *m = JS_NewCModule(ctx, module_name, mailer_init);
    if (!m) return NULL;
    JS_AddModuleExportList(ctx, m, funcs, countof(funcs));
    return m;
}
  1. 编译 QuickJS 并链接 libesmtp:
bash 复制代码
gcc -o qjs mailer.c qjs.c -Iquickjs -lesmtp -lssl -lcrypto
  1. 在 QuickJS 中使用:
javascript 复制代码
import * as mailer from 'mailer';

mailer.send({
  server: 'smtp.example.com:587',
  user: 'your_email@example.com',
  pass: 'your_password',
  from: 'sender@example.com',
  to: 'recipient@example.com',
  subject: '测试邮件',
  body: '邮件正文',
  attachments: ['/path/to/file.txt']
});

注意事项:

  1. curl 方法要求

    • 系统需安装 curl (7.20.0+)
    • 附件需可读且大小不超过邮件服务器限制
    • 敏感信息建议从环境变量读取
  2. 安全建议

    javascript 复制代码
    // 从环境变量读取凭据
    const username = std.getenv('SMTP_USER');
    const password = std.getenv('SMTP_PASS');
  3. Windows 系统

    • 使用 PowerShell 的 Send-MailMessage
    javascript 复制代码
    const psCommand = [
      `Send-MailMessage`,
      `-From '${from}'`,
      `-To '${to}'`,
      `-Subject '${subject}'`,
      `-Body '${body}'`,
      `-Attachments '${attachmentPath}'`,
      `-SmtpServer '${smtpServer.split(':')[0]}'`,
      `-Port ${smtpServer.split(':')[1] || 587}`,
      `-Credential (New-Object System.Management.Automation.PSCredential('${username}', (ConvertTo-SecureString '${password}' -AsPlainText -Force)))`
    ].join(' ');
    
    std.system(`powershell -Command "${psCommand}"`);
  4. 替代方案

    • 使用 HTTP API 发送(如 Mailgun/SendGrid)
    • 调用 Python/Node.js 脚本处理邮件发送

对于简单需求,调用系统命令是最快实现方式。对于复杂应用,建议使用 Node.js 等更成熟的运行时环境。

相关推荐
熊猫_豆豆15 小时前
一个模拟四轴飞行器在随机气流扰动下悬停飞行的交互式3D仿真网页,包含飞行器建模与PID控制算法
javascript·3d·html·四轴无人机模拟飞行
来恩100316 小时前
jQuery选择器
前端·javascript·jquery
前端繁华如梦16 小时前
树上挂苹果还是挂玻璃球?Three.js 程序化果实的完整实现指南
前端·javascript
CDwenhuohuo16 小时前
优惠券组件直接用 uview plus
前端·javascript·vue.js
川冰ICE17 小时前
TypeScript装饰器与元编程实战
前端·javascript·typescript
AI砖家17 小时前
Vue3组件传参大全,各种传参方式的对比
前端·javascript·vue.js
希望永不加班17 小时前
var局部变量类型推断的利弊
java·服务器·前端·javascript·html
threelab18 小时前
Three.js 3D 地图可视化 | 三维可视化 / AI 提示词
前端·javascript·人工智能·3d·着色器
失眠的咕噜18 小时前
PDA 安卓设备上传多张图片
android·前端·javascript
掰头战士19 小时前
深入了解JS原型及原型继承链机制
javascript