我需要从我的服务器端( Node js)发送电子邮件。我浏览了如何在 Node js 中使用 gmail 发送电子邮件,但所有内容都已过时。 Google 去年停用了安全性较低的应用功能。
然后我找到了gmail API。我尝试再次浏览如何使用 gmail api 发送电子邮件,但没有找到任何有用的信息。尝试阅读gmail API文档,但他们没有给出nodejs的示例(仅java和python)。那么谁能告诉我关于如何使用gmail API发送电子邮件的最新方法(2023方法)?或者至少给我一个引用。
最佳答案
开始吧,首先安装nodemailer
(npm i nodemailer
),然后
const nodemailer = require("nodemailer");
const transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 465,
secure: true,
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_KEY
}
});
将 process.env.EMAIL_USER
替换为您的 Gmail 地址,将 process.env.EMAIL_KEY
替换为您的应用密码(从您的 Google 帐户生成>安全> 2FA>应用程序密码),然后
async function sendEmail(email, subject, body) {
const info = await transporter.sendMail({
from: `"SOME NAME" <SENDER EMAIL>`, // sender address //TODO: update
to: email, // list of receivers
subject: subject, // Subject
text: body, // plain text body
// html: "<b>Hello world?</b>", // html body
}).catch(console.error);
return info ? info.messageId : null;
}
if(await sendEmail('<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ce9e1ede5e0ccebe1ede5e0a2efe3e1" rel="noreferrer noopener nofollow">[email protected]</a>', 'subject', 'body')){
console.log('message sent!');
}
关于node.js - 2023年如何在nodejs中使用gmail发送电子邮件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76472151/