Nodemailer 是一个用于 Node.js 环境下的邮件发送库,使用方便,支持多种邮件协议和服务商。在 Express.js 应用程序中使用 Nodemailer 可以很方便地实现邮件发送功能。
安装 Nodemailer
要使用 Nodemailer,首先要安装它。可以使用 npm 包管理器进行安装:
npm install nodemailer --save
安装完成后,可以引入它:
const nodemailer = require('nodemailer');
指定邮件服务商
要使用 Nodemailer 发送邮件,需要提供对应的邮件服务商信息。以 Gmail 为例,可以通过以下方式进行配置:
const transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: 'your_email@gmail.com', // 邮箱地址 pass: 'your_password' // 邮箱密码或授权码 } });
其中,service
属性指定了使用的邮件服务商,auth
属性指定了账号和密码。
编写邮件内容
接下来,需要编写邮件内容。可以使用 HTML 格式编写邮件,如下:
const mailOptions = { from: 'your_email@gmail.com', to: 'recipient_email@gmail.com', subject: '邮件主题', html: '<p>邮件内容</p>' };
其中:
from
属性指定发件人邮箱地址;to
属性指定收件人邮箱地址;subject
属性指定邮件主题;html
属性指定邮件内容,可以使用 HTML 格式。
还可以添加其他属性,如 cc
指定抄送邮箱。
发送邮件
最后,使用 Nodemailer 发送邮件:
transporter.sendMail(mailOptions, function(error, info){ if (error) { console.log(error); } else { console.log('邮件已发送:' + info.response); } });
在发送邮件时,可以指定多个收件人和抄送邮箱。
示例代码
下面是一个完整的 Express.js 应用程序中使用 Nodemailer 实现邮件发送的示例代码:
-- -------------------- ---- ------- ----- ------- - ------------------- ----- ---------- - ---------------------- ----- --- - ---------- -- -- ---------- ----- ----------- - ---------------------------- -------- -------- ----- - ----- ----------------------- -- ---- ----- --------------- -- -------- - --- -- ---- -------------------- ------------- ---- - ----- ----------- - - ----- ----------------------- --- ---------------------------- --- --------------------- -------- ------- ----- ------------- -- --------------------------------- --------------- ------ -- ------- - ------------------- ------------------- - ---- - -------------------- - --------------- ------------------- - --- --- -- ----- ---------------- ---------- - ---------------------- ---
在浏览器中访问 http://localhost:3000/sendmail
,即可触发发送邮件功能。
总结
使用 Express.js 及 Nodemailer 实现邮件发送功能非常方便。只需要安装 Nodemailer,指定邮件服务商,编写邮件内容,然后发送邮件即可。通过该功能,可以让应用程序具备发送邮件的能力,如密码找回、注册验证等需求。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/6549c60d7d4982a6eb4020fd