跳转到内容

Nodemailer

终端窗口
npm install nodemailer
mail.ts
import nodemailer from "nodemailer";
export const transport = nodemailer.createTransport({
host: "smtp.spacepost.dev",
port: 25976,
secure: false, // STARTTLS: the connection is upgraded to TLS before login
requireTLS: true,
auth: { user: "spacepost", pass: process.env.SPACEPOST_API_KEY },
});
await transport.sendMail({
from: '"Acme" <hello@acme.com>',
to: ["user@example.com"],
cc: "manager@example.com",
subject: "Your invoice",
text: "Invoice attached.",
html: '<p>Invoice attached.</p><img src="cid:logo" />',
attachments: [
{ filename: "invoice.pdf", path: "./invoice.pdf" },
{ filename: "logo.png", path: "./logo.png", cid: "logo" },
],
headers: {
"X-SpacePost-Tags": "category=invoice, order_id=1042",
"X-SpacePost-Scheduled-At": "in 1 hour",
},
});

大批量发送时使用连接池:

nodemailer.createTransport({
host: "smtp.spacepost.dev",
port: 25976,
secure: false,
requireTLS: true,
pool: true,
maxConnections: 5,
auth: { user: "spacepost", pass: process.env.SPACEPOST_API_KEY },
});

secure: false 搭配 requireTLS: true 表示使用 STARTTLS:Nodemailer 先以明文连接,在发送你的 API 密钥之前升级到 TLS;如果升级失败,则拒绝继续。暂不提供隐式 TLS(secure: true,465 端口)。

新代码建议使用 Node.js SDK:它会返回邮件的 id 和更丰富的错误信息。