NodeJS 使用 nodemailer 发送邮件

类库依赖

npm install nodemailer --save

导入

  const nodemailer = require("nodemailer");

关键点

  1. 配置 nodemailer.createTransport 的参数,指定 服务地址,端口号,验证的账户和密码
  2. 配置 mailOptions ,from , to 指定发送和目标,邮件内容等。

编写代码示例

 "use strict";
const nodemailer = require("nodemailer");
const MailSettings = require("../config/MailSettings");

// async..await is not allowed in global scope, must use a wrapper
async function sendMailTo(mailUserName, mailContent){

  // Generate test SMTP service account from ethereal.email
  // Only needed if you don't have a real mail account for testing
  let account = await MailSettings.createSenderAccount();

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

  // setup email data with unicode symbols
  let mailOptions = {
    from: '中寰App通知公共邮箱 <app_notice@aerozhonghuan.com>', // sender address
    to: `${mailUserName}@aerozhonghuan.com`, // list of receivers
    subject: mailContent.subject, // Subject line
    // text: mailContent.text, // plain text body
    html: mailContent.html // html body
  };

  // send mail with defined transport object
  let info = await transporter.sendMail(mailOptions);

  console.log("Message sent: %s", info.messageId);
  // Preview only available when sending through an Ethereal account
  console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));

  // Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>
  // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
}

/* 使用 DEMO
let mail = {
  subject: "验证码", // Subject line
  html: "你的验证码是 <B>123</B>", // plain text body
}

sendMail('zhangyunfei',mail).catch(console.error);
*/

参考

https://nodemailer.com/about/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值