Home > Article > Web Front-end > Basic use of nodejs module nodemailer - sample code for sending emails that supports attachments (picture)
This article mainly introduces the basic use of nodejs module nodemailer - email sending example (supports attachments). It has certain reference value. Interested friends can refer to it.
nodemailer is the email sending module in nodejs. The version used in this article is 2.5.0
--Download the module
npm install nodemailer
After downloading the module from npm , you can use it after introducing it in the project: var nodemailer = require('nodemailer');
Take QQ mailbox as an example.
--Get authorization code
Enter QQ personal mailbox, Settings-Account-Enable service POP3/SMTP service, and generate authorization code. Now to obtain authorization code, you need to verify your mobile phone number, etc.
--Backend code
var nodemailer = require('nodemailer'); var transporter = nodemailer.createTransport({ service: 'qq', auth: { user: '527828938@qq.com', pass: 'ugxovfwhvxxxxxx' //授权码,通过QQ获取 } }); var mailOptions = { from: '527828938@qq.com', // 发送者 to: '452076103@qq.com', // 接受者,可以同时发送多个,以逗号隔开 subject: 'nodemailer2.5.0邮件发送', // 标题 //text: 'Hello world', // 文本 html: `<h2>nodemailer基本使用:</h2>` }; transporter.sendMail(mailOptions, function (err, info) { if (err) { console.log(err); return; } console.log('发送成功'); });
--Run result
##--Send attachmentvar transporter = nodemailer.createTransport({ service: 'qq', auth: { user: '527828938@qq.com', pass: 'ugxovfwhvxypxxxx' } }); var mailOptions = { from: '527828938@qq.com', // 发送者 to: '452076103@qq.com', // 接受者,可以同时发送多个,以逗号隔开 subject: 'nodemailer2.5.0邮件发送', // 标题 //text: 'Hello world', // 文本 html: `<h2>nodemailer基本使用:</h2>`, attachments:[ { filename : 'package.json', path: './package.json' }, { filename : 'content', content : '发送内容' } ] }; transporter.sendMail(mailOptions, function (err, info) { if (err) { console.log(err); return; } console.log('发送成功'); });--Run result Download the attachment and open it This should be a good function for sending attachments.
The above is the detailed content of Basic use of nodejs module nodemailer - sample code for sending emails that supports attachments (picture). For more information, please follow other related articles on the PHP Chinese website!