【问题标题】:How to send emails with google using nodemailer after Google disabled less sure app option?(nodemailer)谷歌禁用了谷歌帐户上不太安全的应用程序选项我想找到一种通过谷歌发送电子邮件的方法。或任何其他方式
【发布时间】:2022-06-11 12:05:30
【问题描述】:

我想找到一种方法,通过某种 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

只要谷歌有不太安全的应用选项,它就可以正常工作,但从那以后我一直在努力寻找方法。

【问题讨论】:

标签: node.js oauth-2.0 gmail nodemailer


【解决方案1】:

您应该查看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,
  },
});

【讨论】:

  • 我需要为此设置我的谷歌云平台吗?
  • 您需要在 Google developer console 上启用 gmail api 的项目,在这里您将获得上述代码的客户端 ID 和客户端密码
【解决方案2】:

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

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

只有在开启两步验证的情况下,应用密码才有效。 按照以下步骤获取应用密码

  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"
    }
)

【讨论】:

    猜你喜欢
    • 2022-07-19
    • 2023-01-17
    • 1970-01-01
    • 2012-09-24
    • 1970-01-01
    • 2021-08-27
    • 2017-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多