oauth-2.0 如何发送电子邮件与谷歌使用nodemailer后,谷歌禁用不太确定的应用程序选项?

rjjhvcjd  于 2022-10-31  发布在  其他
关注(0)|答案(2)|浏览(209)

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

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
nhaq1z21

nhaq1z211#

在写这篇文章的时候,谷歌已经不再支持Less Secure Apps了,而且你也不能使用你的谷歌账户密码。
你得生成一个新的应用密码。
应用程序密码仅在两步验证打开时有效。请按照以下步骤获取应用程序密码
1.转到https://myaccount.google.com/security
1.启用2FA
1.创建电子邮件的应用程序密码
1.将该密码(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"
    }
)
rks48beu

rks48beu2#

您应该检查一下Xoauth2
Nodmailer支持多种Oauth类型

let transporter = nodemailer.createTransport({
  host: "smtp.gmail.com",
  port: 465,
  secure: true,
  auth: {
    type: "OAuth2",
    user: "user@example.com",
    clientId: "000000000000-xxx0.apps.googleusercontent.com",
    clientSecret: "XxxxxXXxX0xxxxxxxx0XXxX0",
    refreshToken: "1/XXxXxsss-xxxXXXXXxXxx0XXXxxXXx0x00xxx",
    accessToken: "ya29.Xx_XX0xxxxx-xX0X0XxXXxXxXXXxX0x",
    expires: 1484314697598,
  },
});

相关问题