首页 > 解决方案 > 连接到 Gmail API 的问题

问题描述

我正在努力连接到 Gmail API。我已经完成了设置过程,并在 OAuth 2.0 Playground 上获得了一个工作令牌。我正在尝试从 Node.js / Express / Nodemailer 服务器上的表单发送邮件。当我尝试从我的表单发送邮件时,我在终端中收到以下错误消息:

[0] [nodemon] starting `node Index.js`
[0] Server listening on port 3001
[0] (node:44987) UnhandledPromiseRejectionWarning: Error: unauthorized_client
[0]     at Gaxios.request (/Users/arnepedersen/code/arnelamo/playground-react/my-site/00-email-test/node_modules/gaxios/build/src/gaxios.js:70:23)
[0]     at processTicksAndRejections (internal/process/task_queues.js:85:5)
[0]     at async OAuth2Client.refreshTokenNoCache (/Users/arnepedersen/code/arnelamo/playground-react/my-site/00-email-test/node_modules/google-auth-library/build/src/auth/oauth2client.js:169:21)
[0]     at async OAuth2Client.refreshAccessTokenAsync (/Users/arnepedersen/code/arnelamo/playground-react/my-site/00-email-test/node_modules/google-auth-library/build/src/auth/oauth2client.js:194:19)
[0]     at async OAuth2Client.getAccessTokenAsync (/Users/arnepedersen/code/arnelamo/playground-react/my-site/00-email-test/node_modules/google-auth-library/build/src/auth/oauth2client.js:214:23)
[0] (node:44987) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
[0] (node:44987) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

我的 index.js 看起来像这样:


const express = require('express')
const bodyParser = require('body-parser')
const nodemailer = require('nodemailer')
const app = express()
// npm install nodemailer googleapis
const { google } = require("googleapis");
const OAuth2 = google.auth.OAuth2;

const oauth2Client = new OAuth2(
     // ClientID
     "*****",
     // Client Secret
     "*****",
     // Redirect URL
     "https://developers.google.com/oauthplayground"
);

oauth2Client.setCredentials({
     refresh_token: "*****"
});
const accessToken = oauth2Client.getAccessToken()

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))

app.post('/api/form', (req, res) => {
    nodemailer.createTestAccount((err, accounteé) => {
         const htmlEmail = `
            <h3>Contact Details</h3>
            <ul>
                <li>Name: ${req.body.name}</li>
                <li>Email: ${req.body.email}</li>
            </ul>
            <h3>Message</h3>
            <p>${req.body.message}</p>
         `


         let transporter = nodemailer.createTransport({
             service: "gmail",
             auth: {
                  type: "OAuth2",
                  user: "arne.pedersen.dev@gmail.com",
                  clientId: "some_id",
                  clientSecret: "some_secret",
                  accessToken: accessToken
             }
});

         let mailOptions = {
            from: 'arne.pedersen.dev@gmail.com',
            to: 'arne.pedersen.dev@gmail.com',
            replyTo: 'arne.pedersen.dev@gmail.com',
            subject: 'New message!',
            text: req.body.message,
            html: htmlEmail
         }

         transporter.sendMail(mailOptions, (err, info) => {
            if (err) {
                return console.log(err)
            }

            console.log('Message sent: %s', info.message)
            console.log('Message URL: %s', nodemailer.getTestMessageUrl(info))
         })
    })
})

if (process.env.NODE_ENV === "production") {
    app.use(express.static('client/build'))

    app.get('*', (req, res) => {
        res.sendFile(path.resolve(__dirname, "client", "build", "index.html"))
    })
}

const PORT = process.env.PORT || 3001

app.listen(PORT, () => {
    console.log(`Server listening on port ${PORT}`)
})

标签: javascriptnode.jsexpressgmail-apinodemailer

解决方案


试试这个。我和你有同样的问题,在通过谷歌 API 代码查找了几个小时之后,我能够弄清楚!希望这将帮助您找出代码中的问题。=)

    const { OAuth2 } = google.auth;

    const GMAIL_CLIENT_ID = "";
    const GMAIL_CLIENT_SECRET = "";
    const GMAIL_REFRESH_TOKEN = "";
    const GMAIL_ID = "";
    const OAUTH_PLAYGROUND = "https://developers.google.com/oauthplayground";

    const oauth2Client = new OAuth2(
      GMAIL_CLIENT_ID,
      GMAIL_CLIENT_SECRET,
      OAUTH_PLAYGROUND
    );

    oauth2Client.setCredentials({
      refresh_token: GMAIL_REFRESH_TOKEN,
    });

    google.options({ auth: oauth2Client }); // Apply the settings globally 

    const accessToken = new Promise((resolve, reject) => {
      oauth2Client.getAccessToken((err, token) => {
        if (err) console.log(err); // Handling the errors
        else resolve(token);
      });
    });

    const transporter = nodemailer.createTransport({
      service: "gmail",
      auth: {
        type: "OAuth2",
        user: GMAIL_ID,
        clientId: GMAIL_CLIENT_ID,
        clientSecret: GMAIL_CLIENT_SECRET,
        refreshToken: GMAIL_REFRESH_TOKEN,
        accessToken,
      },
    });

    const mailOptions = {
      from: GMAIL_ID,
      to: "to-email@gmail.com",
      subject: "subject",
      text: "message",
    };

    transporter.sendMail(mailOptions, (err, info) => {
      if (err) {
        console.log(err);
      } else {
        console.log(info);
      }
    });

推荐阅读