在NodeJS中发送邮件

在NodeJS中发送邮件

hash070 1,270 2023-02-25

简介

使用NodeJS中发送邮件是很常见的需求,本篇文章记录一下如何在NodeJS中使用时下流行的NodeMailer库发送邮件。

官方文档:https://nodemailer.com/about/

安装与使用

添加库依赖

请根据自己所使用的包管理工具来安装依赖包。

# NPM
npm install nodemailer
# Yarn
yarn add nodemailer

官方示例

以下为官方示例代码(其中require动态导入被我改成了import静态导入)

这并不会真的发送邮件,只能用来测试邮件效果,在测试环境中也许很有用。邮件“发送”成功后控制台会输出一个网址,你可以在网页中预览这个邮件

image-20230105113605653

image-20230105113718733

//导入邮件依赖包
import * as nodemailer from 'nodemailer';

// async..await is not allowed in global scope, must use a wrapper
async function main() {
  // Generate test SMTP service account from ethereal.email
  // Only needed if you don't have a real mail account for testing
  let testAccount = await nodemailer.createTestAccount();

  // create reusable transporter object using the default SMTP transport
  let transporter = nodemailer.createTransport({
    host: "smtp.ethereal.email",
    port: 587,
    secure: false, // true for 465, false for other ports
    auth: {
      user: testAccount.user, // generated ethereal user
      pass: testAccount.pass, // generated ethereal password
    },
  });

  // send mail with defined transport object
  let info = await transporter.sendMail({
    from: '"Fred Foo 👻" <foo@example.com>', // sender address
    to: "bar@example.com, baz@example.com", // list of receivers
    subject: "Hello ✔", // Subject line
    text: "Hello world?", // plain text body
    html: "<b>Hello world?</b>", // html body
  });

  console.log("Message sent: %s", info.messageId);
  // Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>

  // Preview only available when sending through an Ethereal account
  console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
  // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
}

main().catch(console.error);

MyDemo

用真实的163邮箱的SMTP账号发送个邮件试试

import * as nodemailer from "nodemailer";

export async function mailTest() {
  let transporter = nodemailer.createTransport({
    pool: true, // 启用连接池,保持与邮件服务器的连接
    host: "smtp.163.com", //邮件服务器SMTP地址
    port: 465, //服务器SMTP端口
    secure: true, // 465时true,其它端口填false
    auth: {
      user: "yours@163.com",//SMTP账号
      pass: "password"//SMTP密钥
    }
  });

  // send mail with defined transport object
  let info = await transporter.sendMail({
    from: "\"Node邮件测试\" <yours@163.com>", // sender address
    to: "a@icloud.com, b@icloud.com", // list of receivers
    subject: "NodeJS Mail Test ✔", // Subject line
    text: "Hello Node Mail", // plain text body
    html: "<b>Hello Node Mail</b>" // html body
      //这里也可换成text: "xxx" 用来发送简单的文字
  });

  console.log("邮件发送信息:",info);
}

详解

import导入依赖

使用import * as xxx from xxx来实现包的静态导入。

关于import xxximport * as xxx的区别:https://stackoverflow.com/questions/31386631/difference-between-import-x-and-import-as-x-in-node-js-es6-babel

//导入邮件依赖包
import * as nodemailer from 'nodemailer';

创建与邮件服务器的连接池

使用nodemailercreateTransport()方法来创建一个transporter对象,后面可以使用这个对象来发送邮件

  let transporter = nodemailer.createTransport({
    pool: true, // 启用连接池,保持与邮件服务器的连接
    host: "smtp.163.com", //邮件服务器SMTP地址
    port: 465, //服务器SMTP端口
    secure: true, // 465时true,其它端口填false
    auth: {
      user: "yours@163.com",//SMTP账号
      pass: "password"//SMTP密钥
    }
  });

发送邮件

transportersendMail()是一个异步方法,可以使用await来开始同步等待:

  // send mail with defined transport object
  let info = await transporter.sendMail({
    from: "\"Node邮件测试\" <yours@163.com>", // sender address
    to: "a@icloud.com, b@icloud.com", // list of receivers
    subject: "NodeJS Mail Test ✔", // Subject line
    text: "Hello Node Mail", // plain text body
    html: "<b>Hello Node Mail</b>" // html body
      //这里也可换成text: "xxx" 用来发送简单的文本
  });
//打印发送信息
console.log(info);
/*
{
  accepted: [ 'xxx@icloud.com' ],
  rejected: [],
  envelopeTime: 75,
  messageTime: 86,
  messageSize: 644,
  response: '250 Mail OK queued as zwqz-smtp-mta-g6-1,xxxxxxxxxxxxxx-xxxxxxxxxx',
  envelope: { from: 'xxxxxx@163.com', to: [ 'xxxxxxx@icloud.com' ] },
  messageId: '<xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx@163.com>'
}
*/

也可也使用.then异步执行这个方法:

  // 异步发送邮件
  transporter.sendMail({
    from: "\"Node邮件测试\" <l59y063@163.com>", // sender address
    to: "isolate_wall_0w@icloud.com", // list of receivers
    subject: "NodeJS Mail Test ✔", // Subject line
    text: "Hello Node Mail", // plain text body
    html: "<b>Hello Node Mail</b>" // html body
  }).then((info) => {
    console.log(info);
  })

具体同步还是异步视自己的需求而定。

更多详细信息请查阅:官方文档

更多相关教程:W3Schools-NodeJS-Email