首先需要安装一下nodemailer
#nmp nodemailer install --save
然后就参照官方文档的例程改写一下就行了,代码如下:
'use strict'; const nodemailer = require('nodemailer'); // Generate test SMTP service account from ethereal.email // Only needed if you don't have a real mail account for testing nodemailer.createTestAccount((err, account) => { // create reusable transporter object using the default SMTP transport let transporter = nodemailer.createTransport({ host: 'smtp.163.com', port: 465, secure: true, // true for 465, false for other ports auth: { user: 'abc@163.com', // generated ethereal user pass: 'PASSWORD' // generated ethereal password } }); // setup email data with unicode symbols let mailOptions = { from: 'abc@163.com', // sender address to: 'abc@163.com,def@163.com', // list of receivers subject: '标题:这是一封来自Nodejs发送的邮件', // Subject line text: '你好吗?', // plain text body html: '<b>北京欢迎你</b>' // html body }; // send mail with defined transport object transporter.sendMail(mailOptions, (error, info) => { if (error) { return console.log(error); } 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... }); });
赘述一下:nodemailer的官网在 https://nodemailer.com/about/ ,一般看原文比网文靠谱。