Google 禁用不太确定的应用程序选项后,如何使用 Nodemailer 向 Google 发送电子邮件?

Μελ*_*πας 19 gmail node.js oauth-2.0 nodemailer

我想找到一种方法,nodemailer通过某种谷歌身份验证或任何其他方式从我的应用程序向用户发送电子邮件。在 Google 禁用不太安全的应用程序选项后,下面提到的工作代码已停止工作。

const nodemailer = require('nodemailer')

const sendEmail = async options => {
const transporter = nodemailer.createTransport({
    // host: "smtp.gmail.com",
    // port: "465",
    // secure: true,
    service:'gmail',
    auth: {
        user: "USER_EMAIL",
        pass: "USER_PASSWORD"
    },
    tls:{rejectUnauthorized:false}
})

const message = {
    from: `${process.env.FROM_NAME} <${process.env.FROM_EMAIL}>`,
    to: options.email,
    subject: options.subject,
    text: options.message,
    html: options.message,
    attachments: [
        {
            filename: '.png',
            path: __dirname + '.png',
            cid: '.png'
        }
    ]
}

const info = await transporter.sendMail(message)
console.log('Message sent : %s', info.messageId)
console.log(__dirname)
}
module.exports = sendEmail
Run Code Online (Sandbox Code Playgroud)

小智 43

在撰写本文时,谷歌不再支持不太安全的应用程序。而且你不能使用你的谷歌帐户密码。

您必须生成一个新的应用程序密码。

仅当开启两步验证时,应用程序密码才有效。按照以下步骤获取应用程序密码

  1. 转到https://myaccount.google.com/security
  2. 启用 2FA
  3. 为电子邮件创建应用程序密码
  4. 将该密码(16 个字符)复制到 Nodemailer auth 中的 pass 参数中。
const client = nodemailer.createTransport({
    service: "Gmail",
    auth: {
        user: "username@gmail.com",
        pass: "Google-App-Password-Without-Spaces"
    }
});

client.sendMail(
    {
        from: "sender",
        to: "recipient",
        subject: "Sending it from Heroku",
        text: "Hey, I'm being sent from the cloud"
    }
)
Run Code Online (Sandbox Code Playgroud)