javascript - Gmail API发送电子邮件错误401 :Invalid Credentials

标签 javascript node.js gmail-api google-api-nodejs-client

我正在使用 Express 开发一个网页,当客户点击“发送电子邮件”时,会重定向到 Google,请求通过客户电子邮件发送电子邮件的权限,并在客户授予权限后重定向回来并发送电子邮件.

到目前为止的代码:

'use strict';

const express = require('express');
const googleAuth = require('google-auth-library');
const request = require('request');

let router = express.Router();
let app = express();

const SCOPES = [
    'https://mail.google.com/'
    ,'https://www.googleapis.com/auth/gmail.modify'
    ,'https://www.googleapis.com/auth/gmail.compose'
    ,'https://www.googleapis.com/auth/gmail.send'
];
const clientSecret = '***********';
const clientId = '**************'; 
const redirectUrl = 'http://localhost:8080/access-granted';
const auth = new googleAuth();
const oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
const authUrl = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES
});

function sendEmail(auth, content, to , from, subject) {
    let encodedMail = new Buffer(
        `Content-Type: text/plain; charset="UTF-8"\n` +
        `MIME-Version: 1.0\n` +
        `Content-Transfer-Encoding: 7bit\n` +
        `to: ${to}\n` +
        `from: ${from}\n` +
        `subject: ${subject}\n\n` +

        content
    )
    .toString(`base64`)
    .replace(/\+/g, '-')
    .replace(/\//g, '_');

    request({
        method: "POST",
        uri: `https://www.googleapis.com/gmail/v1/users/me/messages/send`,
        headers: {
            "Authorization": `Bearer ${auth}`,
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            "raw": encodedMail
        })
    },
    function(err, response, body) {
        if(err){
            console.log(err); // Failure
        } else {
            console.log(body); // Success!
        }
    });

}

app.use('/static', express.static('./www'));
app.use(router)

router.get('/access-granted', (req, res) => {
    sendEmail(req.query.code, 'teste email', 'teste@gmail.com', 'teste@gmail.com', 'teste');
    res.sendfile('/www/html/index.html', {root: __dirname})
})

router.get('/request-access', (req, res) => {
    res.redirect(authUrl);
});

router.get('/', (req, res) => {
    res.sendFile('/www/html/index.html', { root: __dirname });
});

const port = process.env.PORT || 8080;
app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
});

module.exports = app;

每次我尝试发送简单的电子邮件时,都会收到错误 401:无效凭据。但我正在传递谷歌发送的客户端代码身份验证给我的授权...

最佳答案

使用 google API 的推荐方法是使用 Google API nodejs client它还提供 Google OAuth 流程。然后,您可以使用 google.gmail('v1').users.messages.send 发送电子邮件:

const gmail = google.gmail('v1');

gmail.users.messages.send({
    auth: oauth2Client,
    userId: 'me',
    resource: {
        raw: encodedMail
    }
}, function(err, req) {
    if (err) {
        console.log(err);
    } else {
        console.log(req);
    }
});

authOAuth2,即可以使用您的 token 填充的 OAuth 对象。您可以在 express session 中获取 token :

var oauth2Client = getOAuthClient();
oauth2Client.setCredentials(req.session["tokens"]);

您已将其存储在 OAuth 回调端点中:

var oauth2Client = getOAuthClient();
var session = req.session;
var code = req.query.code;
oauth2Client.getToken(code, function(err, tokens) {
    // Now tokens contains an access_token and an optional refresh_token. Save them.
    if (!err) {
        oauth2Client.setCredentials(tokens);
        session["tokens"] = tokens;
        res.send(`<html><body><h1>Login successfull</h1><a href=/send-mail>send mail</a></body></html>`);
    } else {
        res.send(`<html><body><h1>Login failed</h1></body></html>`);
    }
});

这是一个完整的示例,灵感来自 this google API oauth for node.js example :

'use strict';

const express = require('express');
const google = require('googleapis');
const request = require('request');
const OAuth2 = google.auth.OAuth2;
const session = require('express-session');
const http = require('http');

let app = express();

app.use(session({
    secret: 'some-secret',
    resave: true,
    saveUninitialized: true
}));

const gmail = google.gmail('v1');

const SCOPES = [
    'https://mail.google.com/',
    'https://www.googleapis.com/auth/gmail.modify',
    'https://www.googleapis.com/auth/gmail.compose',
    'https://www.googleapis.com/auth/gmail.send'
];

const clientSecret = 'CLIENT_SECRET';
const clientId = 'CLIENT_ID';
const redirectUrl = 'http://localhost:8080/access-granted';

const mailContent = "test";
const mailFrom = "someemail@gmail.com";
const mailTo = "someemail@gmail.com";
const mailSubject = "subject";

function getOAuthClient() {
    return new OAuth2(clientId, clientSecret, redirectUrl);
}

function getAuthUrl() {
    let oauth2Client = getOAuthClient();

    let url = oauth2Client.generateAuthUrl({
        access_type: 'offline',
        scope: SCOPES,
        //use this below to force approval (will generate refresh_token)
        //approval_prompt : 'force'
    });
    return url;
}

function sendEmail(auth, content, to, from, subject, cb) {
    let encodedMail = new Buffer(
            `Content-Type: text/plain; charset="UTF-8"\n` +
            `MIME-Version: 1.0\n` +
            `Content-Transfer-Encoding: 7bit\n` +
            `to: ${to}\n` +
            `from: ${from}\n` +
            `subject: ${subject}\n\n` +
            content
        )
        .toString(`base64`)
        .replace(/\+/g, '-')
        .replace(/\//g, '_');

    gmail.users.messages.send({
        auth: auth,
        userId: 'me',
        resource: {
            raw: encodedMail
        }
    }, cb);
}

app.use('/send-mail', (req, res) => {
    let oauth2Client = getOAuthClient();
    oauth2Client.setCredentials(req.session["tokens"]);
    sendEmail(oauth2Client, mailContent, mailTo, mailFrom, mailSubject, function(err, response) {
        if (err) {
            console.log(err);
            res.send(`<html><body><h1>Error</h1><a href=/send-mail>send mail</a></body></html>`);
        } else {
            res.send(`<html><body><h1>Send mail successfull</h1><a href=/send-mail>send mail</a></body></html>`);
        }
    });
});

app.use('/access-granted', (req, res) => {

    let oauth2Client = getOAuthClient();
    let session = req.session;
    let code = req.query.code;
    oauth2Client.getToken(code, function(err, tokens) {
        // Now tokens contains an access_token and an optional refresh_token. Save them.
        if (!err) {
            oauth2Client.setCredentials(tokens);
            session["tokens"] = tokens;
            res.send(`<html><body><h1>Login successfull</h1><a href=/send-mail>send mail</a></body></html>`);
        } else {
            res.send(`<html><body><h1>Login failed</h1></body></html>`);
        }
    });
})

app.use('/', (req, res) => {
    let url = getAuthUrl();
    res.send(`<html><body><h1>Authentication using google oAuth</h1><a href=${url}>Login</a></body></html>`)
});

let port = process.env.PORT || 8080;
let server = http.createServer(app);
server.listen(port);
server.on('listening', function() {
    console.log(`listening to ${port}`);
});

关于javascript - Gmail API发送电子邮件错误401 :Invalid Credentials,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44838927/

相关文章:

ruby-on-rails - 如何通过 GMAIL API 发送带有 BCC header 的电子邮件?

javascript - 如何在Angular 5应用程序中从Gmail API获取authorization_code

javascript - Firestore 错误 : Cannot use multiple conditional where clauses on different properties

javascript - 跟踪文件

javascript - AngularJS 指令不会根据范围变量更改进行更新

javascript - 在 NodeJS 中 fork

node.js - DialogFlow v2 错误 : Resource name '' does not match 'projects/*/locations/*/agent/environments/*/users/*/sessions/*'

javascript - 发布请求正文谷歌API

javascript - 如何在使用 Simplebar js 时以编程方式滚动到 div 的底部

javascript - node.js 中的异步编程是否可以加速 CPU 密集型任务?