Node.js 是一个基于 V8 引擎的服务器端 JavaScript 运行环境,它可以让 JavaScript 代码在服务器端运行,也可以用来开发前端应用程序。本文将介绍如何使用 Node.js 进行邮件发送。
准备工作
在进行邮件发送之前,需要安装 nodemailer 这个 Node.js 的邮件发送库,可以通过 npm 安装:
npm install nodemailer
发送邮件
使用 nodemailer 发送邮件的步骤如下:
创建一个 nodemailer 对象:
-- -------------------- ---- ------- ----- ---------- - ---------------------- ----- ----------- - ---------------------------- ----- ----------------- ----- ---- ------- ----- -- -- --- ----- - ----- ---------------------- ----- -------------- - ---
在上面的代码中,我们配置了发件人的邮箱地址和密码。这里以 Gmail 帐号为例,如果你使用其他邮件服务商,可以对应修改 host 和 port 参数。
创建一个邮件对象:
const mailOptions = { from: 'youremail@gmail.com', to: 'recipientemail@example.com', subject: 'Testing Email using Node.js', text: 'Hello World!', html: '<p>Hello World!</p>' };
在上面的代码中,我们指定了收件人的邮箱地址、邮件标题、纯文本内容和 HTML 内容。
发送邮件:
transporter.sendMail(mailOptions, (error, info) => { if (error) { console.log(error); } else { console.log('Email sent: ' + info.response); } });
在上面的代码中,我们使用 sendMail 方法来发送邮件,可以监听回调函数获取发送结果。
特殊情况
在使用 Gmail 帐号发送邮件时遇到 Less Secure App 问题
如果使用 Gmail 帐号发送邮件时遇到 Less Secure App 问题,可以按照下面的步骤解决:
登录 Gmail 帐户,并进入以下页面:https://www.google.com/settings/security/lesssecureapps
打开“允许较不安全的应用:是”
发送带附件的邮件
如果要发送带附件的邮件,可以按照下面的代码编写:
-- -------------------- ---- ------- ----- ----------- - - ----- ---------------------- --- ----------------------------- -------- -------- ----- ----- --------- ----- ------ -------- ----- --------- ------------ ------------ - - --------- ------------ -------- ------ ------- -- - --------- ------------ ----- -------------------- - - -- --------------------------------- ------- ----- -- - -- ------- - ------------------- - ---- - ------------------ ----- - - --------------- - ---
在上面的代码中,我们使用 attachments 参数来配置附件。
结语
使用 Node.js 进行邮件发送可以轻松地实现邮件的自动化发送,opeo好用又不失灵活性,希望本文能对读者有所帮助。
Source: FunTeaLearn,Please indicate the source for reprints https://funteas.com/post/677fba81ce7f48612512783e