可以使用Google Cloud的OAuth2发送NodeMailer(响应:530)

发布于 2025-02-09 05:51:01 字数 6371 浏览 3 评论 0 原文

我已经配置了两个Gmail帐户,以集成 NodeMailer oauth2 来自 Google Cloud ,我第一次完成它,我可以成功发送Gmail的电子邮件来自我的Nodejs应用程序。但是,今天,我已经做出了以前已经做过的相同的步骤,当我尝试发送电子邮件时,这是错误的。

错误:邮件命令失败:530-5.7.0所需的身份验证

在Internet上进行一些答案,我需要激活在Google上更不安全的应用程序,但是自2022年5月以来,此选项已被Google停用,所以我做不到。

我为在Google Cloud上设置OAuth2的所有步骤(摘要):

  1. 创建新项目

  2. Eneabled Services和API的

  3. oauth同意屏幕上创建了一个新的OAuth2

  4. OAuth2 “> https://developers.google.com/oauthplayground

  5. p>在OAuth同意屏幕上添加测试用户

  6. oauthplayground 选择'https://mail.google.com' client_secret,然后单击代币的交换授权代码

当我需要与gmail配置nodejs时,这是我总是这样做的,我应该工作,然后我将所有必要值复制到node.js client_id,client_secret,refresh_tokens ...


现在我想共享重要的 .js 分别与NodeMailer和Googleapis相关的文件:

const nodemailer = require('nodemailer');
const urlUtil = require('../utils/urlUtil');
const config = require(urlUtil.getPath('../config.min.js'));
const googleApiUtil = require(urlUtil.getPath('../utils/googleApiUtil.min.js'));

/**
 * Send generic email
 * @param {*} destination to
 * @param {*} subject title of the email
 * @param {*} html html content for email template
 * @returns promise
 */
function sendEmail(destination, subject, html) {

    return new Promise((resolve) => {
        googleApiUtil.getCredentials().then((credentials) => {
            try {
                let transporter = nodemailer.createTransport({
                    service: config.mail.service,
                    auth: {
                        type: 'OAuth2',
                        user: config.mail.user,
                        clientId: credentials.client_id,
                        clientSecret: credentials.client_secret,
                        refreshToken: credentials.refresh_token,
                        accessToken: credentials.accessToken
                    }, tls: {
                        rejectUnauthorized: false
                    }

                });
                let mailOptions = {};

                mailOptions = {
                    from: `IARA <${config.mail.user}>`,
                    to: destination,
                    subject: subject,
                    html: html,
                    attachments: null

                };

                transporter.sendMail(mailOptions, resolve);
            } catch (error) {
                console.log(error);
            }
        });

    });
}

//This should send an email to destinantion
sendEmail('[email protected]','teste','testando').then(r=> {
    console.log(r)
})

/**
 * Exports
 */
module.exports = {
    sendEmail
};

const {google} = require('googleapis');
const urlUtil = require('../utils/urlUtil');
const config = require(urlUtil.getPath('../config.min.js'));
const fsUtil = require(urlUtil.getPath('../utils/fsUtil.min.js'));
//Basic credentials
const CLIENT_ID = '4123123..';
const CLIENT_SECRET = 'GO...';

//https://developers.google.com/oauthplayground
const REDIRECT_URI = 'https://developers.google.com/oauthplayground';
let refresh_token = '';
let accessToken = '';

if (!config.mail.refresh_token) {
    refresh_token = '1//...';
} else {
    refresh_token = config.mail.refresh_token;
}

const oAuth2Client = new google.auth.OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI);


oAuth2Client.setCredentials({
    refresh_token: refresh_token,
});

oAuth2Client.refreshAccessToken((err, tokens) => {
    console.log(tokens)
    accessToken = tokens['access_token'];
    refresh_token = tokens['refresh_token'];
    //Set Config
    if (err) {
        console.log(err);
    }
    config.mail.accessToken = accessToken;
    config.mail.refresh_token = refresh_token;
    fsUtil.updateCredentials(config);
});

/**
 * @returns Get credentials
 */
async function getCredentials() {
    return {
        redirect_uri: REDIRECT_URI,
        refresh_token: refresh_token,
        client_id: CLIENT_ID,
        client_secret: CLIENT_SECRET,
        accessToken: accessToken
    };
}


module.exports = {
    getCredentials
};

结论:

我什至不知道我的错误是在OAuth2配置上还是在Nodejs上,我相信它在Google Cloud上,但是我不确定,如果有人,如果有人更有经验的知道我如何解决它,让我知道,感谢Lott

Fullstack的痕迹:

错误:邮件命令失败:530-5.7.0需要身份验证。了解更多信息 530 5.7.0 https://support.google.com/mail/mail/mail/?p=wantautherror < /a> dy43-20020A056870C7AB00B00B001CDB417F1SM5627633OAB.22 -GSMTP 在smtpConnection._formaterror(c:\ javascript Projects \ iara-backend \ node_modules \ nodemailer \ lib \ smtp-connection \ index.js:784:19) 在smtpconnection._actionmail(c:\ javascript Projects \ iara-backend \ node_modules \ nodemailer \ lib \ smtp-connection \ index.js:1566:34) 在SMTPConnection。 (c:\ javascript项目\ iara-backend \ node_modules \ nodemailer \ lib \ smtp-connection \ index.js:1041:18) 在smtpConnection._processresponse(c:\ javascript Projects \ iara-backend \ node_modules \ nodemailer \ lib \ smtp-connection \ index.js:947:20) 在smtpConnection._ondata(c:\ javascript Projects \ iara-backend \ node_modules \ nodemailer \ lib \ lib \ smtp-connection \ index.js:749:14)
在tlssocket.smtpconnection._onsocketdata(c:\ javascript Projects \ iara-backend \ node_modules \ nodemailer \ lib \ lib \ smtp-connection \ smtp-connection \ index.js:189:44) 在tlssocket.emit(events.js:315:20) 在AddChunk(内部/流/可读取.js:309:12) 在ReadableAddchunk(内部/流/可READABLE.JS:284:9) 在tlssocket.preable.push(内部/streams/readable.js:223:10){ 代码:'eenvelope', 响应:'530-5.7.0需要身份验证。在\ n' +上了解更多信息 '530 5.7.0 https://support.google.com/mail/?p=wantautherror dy43-20020a056870c70b00b00b00101cdb417f1sm5627627633oab.22- 响应:530, 命令:“来自”的邮件 }

I've already configured two GMAIL accounts to integrate nodemailer with Oauth2 from Google cloud, the first time I've done it I could successfully send GMAIL's email from my nodejs application. However, today I've made the same steps I've already done before and It's throwing an error when I try to send an e-mail.

Error: Mail command failed: 530-5.7.0 Authentication Required

Some answers on internet says I need to activate less secure app on google, but since May,2022 this option was deactivate by google, so I can't do it.

All the steps I made to set up the Oauth2 on Google cloud (summary):

  1. Create a new project

  2. Eneabled services and API's

  3. Created a new Oauth2 on OAuth consent screen

  4. Created new credential, web application, with redirecting: https://developers.google.com/oauthplayground

  5. Added test users on OAuth consent screen

  6. On oauthplayground selected 'https://mail.google.com' service and added CLIENT_ID and CLIENT_SECRET, then click on Exchange authorization code for tokens

This is the same set up I always do when I need to configure nodejs with GMAIL, I should work, then I copy all necessary values to node.js CLIENT_ID , CLIENT_SECRET, refresh_tokens ...


Now I would like to share to important .js files related with nodemailer and GoogleApis, respectively:

const nodemailer = require('nodemailer');
const urlUtil = require('../utils/urlUtil');
const config = require(urlUtil.getPath('../config.min.js'));
const googleApiUtil = require(urlUtil.getPath('../utils/googleApiUtil.min.js'));

/**
 * Send generic email
 * @param {*} destination to
 * @param {*} subject title of the email
 * @param {*} html html content for email template
 * @returns promise
 */
function sendEmail(destination, subject, html) {

    return new Promise((resolve) => {
        googleApiUtil.getCredentials().then((credentials) => {
            try {
                let transporter = nodemailer.createTransport({
                    service: config.mail.service,
                    auth: {
                        type: 'OAuth2',
                        user: config.mail.user,
                        clientId: credentials.client_id,
                        clientSecret: credentials.client_secret,
                        refreshToken: credentials.refresh_token,
                        accessToken: credentials.accessToken
                    }, tls: {
                        rejectUnauthorized: false
                    }

                });
                let mailOptions = {};

                mailOptions = {
                    from: `IARA <${config.mail.user}>`,
                    to: destination,
                    subject: subject,
                    html: html,
                    attachments: null

                };

                transporter.sendMail(mailOptions, resolve);
            } catch (error) {
                console.log(error);
            }
        });

    });
}

//This should send an email to destinantion
sendEmail('[email protected]','teste','testando').then(r=> {
    console.log(r)
})

/**
 * Exports
 */
module.exports = {
    sendEmail
};

const {google} = require('googleapis');
const urlUtil = require('../utils/urlUtil');
const config = require(urlUtil.getPath('../config.min.js'));
const fsUtil = require(urlUtil.getPath('../utils/fsUtil.min.js'));
//Basic credentials
const CLIENT_ID = '4123123..';
const CLIENT_SECRET = 'GO...';

//https://developers.google.com/oauthplayground
const REDIRECT_URI = 'https://developers.google.com/oauthplayground';
let refresh_token = '';
let accessToken = '';

if (!config.mail.refresh_token) {
    refresh_token = '1//...';
} else {
    refresh_token = config.mail.refresh_token;
}

const oAuth2Client = new google.auth.OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI);


oAuth2Client.setCredentials({
    refresh_token: refresh_token,
});

oAuth2Client.refreshAccessToken((err, tokens) => {
    console.log(tokens)
    accessToken = tokens['access_token'];
    refresh_token = tokens['refresh_token'];
    //Set Config
    if (err) {
        console.log(err);
    }
    config.mail.accessToken = accessToken;
    config.mail.refresh_token = refresh_token;
    fsUtil.updateCredentials(config);
});

/**
 * @returns Get credentials
 */
async function getCredentials() {
    return {
        redirect_uri: REDIRECT_URI,
        refresh_token: refresh_token,
        client_id: CLIENT_ID,
        client_secret: CLIENT_SECRET,
        accessToken: accessToken
    };
}


module.exports = {
    getCredentials
};

Conclusion:

I not even know if my mistake is on Oauth2 configuration or in Nodejs, I belive it's on Google cloud, but I'm not really sure, If anyone more experienced know how I can solve it let me know, Thanks a lott

Fullstack trace:

Error: Mail command failed: 530-5.7.0 Authentication Required. Learn more at
530 5.7.0 https://support.google.com/mail/?p=WantAuthError dy43-20020a056870c7ab00b00101cdb417f1sm5627633oab.22 - gsmtp
at SMTPConnection._formatError (c:\Javascript Projects\IARA-backend\node_modules\nodemailer\lib\smtp-connection\index.js:784:19)
at SMTPConnection._actionMAIL (c:\Javascript Projects\IARA-backend\node_modules\nodemailer\lib\smtp-connection\index.js:1566:34)
at SMTPConnection. (c:\Javascript Projects\IARA-backend\node_modules\nodemailer\lib\smtp-connection\index.js:1041:18)
at SMTPConnection._processResponse (c:\Javascript Projects\IARA-backend\node_modules\nodemailer\lib\smtp-connection\index.js:947:20)
at SMTPConnection._onData (c:\Javascript Projects\IARA-backend\node_modules\nodemailer\lib\smtp-connection\index.js:749:14)
at TLSSocket.SMTPConnection._onSocketData (c:\Javascript Projects\IARA-backend\node_modules\nodemailer\lib\smtp-connection\index.js:189:44)
at TLSSocket.emit (events.js:315:20)
at addChunk (internal/streams/readable.js:309:12)
at readableAddChunk (internal/streams/readable.js:284:9)
at TLSSocket.Readable.push (internal/streams/readable.js:223:10) {
code: 'EENVELOPE',
response: '530-5.7.0 Authentication Required. Learn more at\n' +
'530 5.7.0 https://support.google.com/mail/?p=WantAuthError dy43-20020a056870c7ab00b00101cdb417f1sm5627633oab.22 - gsmtp',
responseCode: 530,
command: 'MAIL FROM'
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浮萍、无处依 2025-02-16 05:51:01

我刚刚解决了这个问题,即我获得的最佳解决方案,每当我致电 oauth2client.refreshaccesstoken()函数时,我保存了所有返回的凭据,例如 refresh_token accept_token 在配置文件(.json)上,因此,当我致电发送电子邮件时,我从配置文件中获得了这些凭据更新。实际上,这很容易,很抱歉在Stackoverflow上打开一个愚蠢的问题。

I've just solved the issue, the best solution I got, whenever I call the oAuth2Client.refreshAccessToken() function I save all returned credentials such as refresh_token, access_token on a config file (.json), so when I call to send e-mail I got those credentials updated from config file. It's was quite easy actually, sorry for open a silly question here on Stackoverflow.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文