本文探索了如何利用nodemailer库在本地应用api的形式来发送电子邮件。

nodemailer官网

装置

npm install nodemailer -S

根本实现

// @doc https://nodemailer.com/const nodemailer = require("nodemailer");async function main() {  let transporter = nodemailer.createTransport({    // 反对465和587,二者都能够    port: 587,    secure: false, // true for 465, false for other ports    // port: 465,    // secure: true,    // 服务起源:163邮箱    service: "163",    auth: {      user: "frost@163.com",      // 邮箱SMTP受权码,很重要,相当于一般的邮箱明码      // @question https://note.youdao.com/ynoteshare1/index.html?id=f9fef46114fb922b45460f4f55d96853&type=note      pass: "xxx",    },  });  let info = await transporter.sendMail({    from: '"frost" <frost@163.com>', // sender address    to: "xx@163.com,xxx@qq.com", // list of receivers    subject: "Hello ✔", // Subject line    html: "<b>Hello world2?</b>", // html body  });  console.log("Message sent: %s", info.messageId);}main().catch(console.error);

间接node index.js即可运行,去邮箱查看邮件吧。

这里的邮箱SMTP受权码须要在对应的邮箱设置中获取。

163邮箱-如何开启客户端受权码?

增加附件

const path = require("path");  async function main() {   let info = await transporter.sendMail({    // ...    attachments: [      {        filename: "hello.txt",        content: "hello world",      },      {        filename: "network_image.jpg",        href: "https://img0.baidu.com/it/u=3212920999,1827079299&fm=26&fmt=auto&gp=0.jpg",      },      {        filename: "local.txt",        path: path.resolve(__dirname, "local.txt"),      },    ],  });}

其中第三个文件是在本地新建一个txt文件,发现附件曾经带上了。

更多

HTML模板-Documentation for MJML