美文网首页程序员
NodeJS 使用 nodemailer 发送邮件

NodeJS 使用 nodemailer 发送邮件

作者: 张云飞Vir | 来源:发表于2019-03-05 17:03 被阅读0次

    类库依赖

    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/

    相关文章

      网友评论

        本文标题:NodeJS 使用 nodemailer 发送邮件

        本文链接:https://www.haomeiwen.com/subject/rzyouqtx.html