嗨👋,我是阿巴约米。
一位对后端感兴趣的软件工程师
软件工程师
-
📝 我的作品集点击这里
-
📫 如何联系我abayomiogunnusi@gmail.com
-
📄了解我的经历https://www.linkedin.com/in/abayomi-ogunnusi-974826141/
嘿,各位!今天我们将学习如何使用 NodeJS 直接从我们的 IDE 发送电子邮件。我们要用到的模块叫做 Nodemailer。
🔗 Node.js
🔗 Nodemailer
🔗 电子邮件帐户
🎯 步骤:
打开编辑器(VSCode 😁),使用以下命令初始化项目。
npm init -y
此命令会启动一个package.json、package.json.lock一个和index.js(主入口文件)。该文件index.js将容纳我们所有的逻辑。
📌安装 Nodemailer
npm i nodemailer
📌导入包裹index.js
const nodemailer = require('nodemailer');
👨🏽🏫 出于安全考虑,请务必安装并使用dot.env包,以防止您的密码泄露或推送到 GitHub。Install dotenv
npm i dotenv -S
请在文件中引入 dotenv index.js。由于本项目中使用的是虚拟数据,因此我没有引入它。
require('dotenv').config();
然后,创建一个.env文件,其中包含您的电子邮件地址和密码。
Email= ***********@gmail.com
Password= ******
🎯 你的身份验证逻辑index.js在dotenv
// Gmail account info
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL,
pass: process.env.PASSWORD
}
});
🎯 你的身份验证逻辑index.js无需任何代码dotenv。请在下方编写逻辑,当然,也要将邮箱和密码替换成你自己的邮箱和密码。
// Gmail account info
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'dsimple@gmail.com',
pass: 'ilovemymama'
}
});
🎯 接下来使用 mailOption 发送您的消息。
// Email info
const mailOptions = {
from: 'dsimple@gmail.com',
to: 'fams@gmail.com',
subject: 'How to send emails using NodeJS',
text: 'Follow the instructions and you will be fine'
};
🎯 最后,请写:
// Send email 📧 and retrieve server response
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
如果操作得当,你的代码中应该包含以下逻辑index.js。也就是说,如果你选择不使用……dotenv 
运行方法:在终端中输入👇🏼
node index
注意:在您的 Gmail 中,请务必允许“安全性较低的应用”访问您的脚本,以便 Gmail SMTP 连接能够正常运行。如果此选项处于关闭状态,Gmail 会发出错误提示,您需要将其开启。
const mailOptions = {
from: 'dsimple@gmail.com',
to: 'fams@gmail.com,myrealfams@gmail.com',
cc: 'lexus@gmail.com',
bcc: 'sugar@gmail.com',
subject: 'How to send emails using NodeJS',
text: 'Follow the instructions and you will be fine'
};
const mailOptions = {
from: 'dsimple@gmail.com',
to: 'fams@gmail.com,myrealfams@gmail.com',
cc: 'lexus@gmail.com',
bcc: 'sugar@gmail.com',
subject: 'How to send emails using NodeJS',
text: 'Follow the instructions and you will be fine',
attachments: [{
filename: "robocop.jpg", path: "./img/robocop.jpg"}]
};
一位对后端感兴趣的软件工程师
📝 我的作品集点击这里
📫 如何联系我abayomiogunnusi@gmail.com
📄了解我的经历https://www.linkedin.com/in/abayomi-ogunnusi-974826141/
除了 Gmail 之外,还有哪些电子邮件服务可以在不关闭“允许安全性较低的应用使用”设置的情况下使用?
下载 Node.js
npm 参考
Nodemailer 网站