API: 电子邮件 (SMTP)

通过 SMTP 服务器发送电子邮件的函数。

C++ 注册:regEmail(js)。 实现文件:jsEmail.h


send_email

send_email(config: object) → object

通过 SMTP 发送电子邮件。

参数 (config 对象的字段):

字段 类型 必需 描述
host 字符串 SMTP 服务器
port 数字 端口 (25, 465, 587)
user 字符串 SMTP 认证登录名
pass 字符串 密码
ssl 布尔值 true — SMTPS (从一开始就使用 SSL,通常是端口 465)
starttls 布尔值 true — STARTTLS (连接升级,通常是端口 587)
from 对象 发件人 (见下文)
to 对象 收件人 (见下文)
subject 字符串 邮件主题
body 字符串 邮件正文 (纯文本)

fromto 的字段:

字段 类型 描述
email 字符串 电子邮件地址
name 字符串 显示名称

结果:

字段 类型 描述
code 数字 0 — 成功,负数 — 错误
log 字符串 SMTP 对话日志 (用于调试)
error 字符串 错误消息或 ""

连接模式

模式 端口 配置
SMTPS (SSL) 465 ssl: true
STARTTLS 587 starttls: true
普通 SMTP 25 无需标志

示例

Office 365

let r = send_email({
    host: "smtp.office365.com",
    port: 587,
    ssl: false,
    starttls: true,
    user: "user@yourdomain.com",
    pass: "your_password",
    from: { email: "user@yourdomain.com", name: "系统邮件程序" },
    to:   { email: "admin@example.com",   name: "管理员" },
    subject: "警报:服务不可用",
    body: "MyService 在 14:35 停止响应。"
});

if (r.code === 0) {
    console.log("邮件已发送");
} else {
    console.log("错误:", r.error);
    console.log("SMTP 日志:", r.log);
}

Gmail (应用专用密码)

Gmail 需要使用应用专用密码,而不是您的常规密码。 启用方法:Google 帐户 → 安全性 → 两步验证 → 应用专用密码。 注意:Gmail 已不再支持 SMTP。

本地 SMTP (无 TLS)

let r = send_email({
    host: "mail.internal.corp",
    port: 25,
    ssl: false,
    starttls: false,
    user: "mailer@internal.corp",
    pass: "password",
    from: { email: "mailer@internal.corp", name: "邮件程序" },
    to:   { email: "admin@internal.corp", name: "管理员" },
    subject: "警报",
    body: "出现错误"
});

通过配置发送

配置文件 CaEmail.json:

{
  "scriptfile": "./email_send.js",
  "arg": {
    "host": "smtp.office365.com",
    "port": 587,
    "ssl": false,
    "starttls": true,
    "user": "user@yourdomain.com",
    "pass": "CHANGE_ME",
    "from": {
      "email": "user@yourdomain.com",
      "name": "系统邮件程序"
    },
    "to": {
      "email": "recipient@example.com",
      "name": "收件人"
    },
    "subject": "测试消息",
    "body": "这是一封来自 JsN 的测试邮件"
  }
}

脚本 email_send.js:

let resp = send_email({
    host:     arg.host,
    port:     arg.port,
    ssl:      arg.ssl,
    starttls: arg.starttls,
    user:     arg.user,
    pass:     arg.pass,
    from:     arg.from,
    to:       arg.to,
    subject:  arg.subject,
    body:     arg.body
});

console.log(JSON.stringify(resp, null, 2));
JsN.exe CaEmail.json

SMTP 调试

出错时,打印 r.log — 它包含完整的 SMTP 对话日志:

let r = send_email({ ... });
if (r.code !== 0) {
    console.log("=== SMTP 日志 ===");
    console.log(r.log);
    console.log("=== 错误 ===");
    console.log(r.error);
}