Javascript 连接到Gmail API时出现问题

Javascript 连接到Gmail API时出现问题,javascript,node.js,express,gmail-api,nodemailer,Javascript,Node.js,Express,Gmail Api,Nodemailer,我正在努力连接到Gmail API。我已经完成了安装过程,并在OAuth2.0平台上获得了一个工作令牌。我正在尝试从Node.js/Express/nodeEmailer服务器上的表单发送邮件。当我尝试从我的表单发送邮件时,我在终端中收到以下错误消息: [0] [nodemon] starting `node Index.js` [0] Server listening on port 3001 [0] (node:44987) UnhandledPromiseRejectionWarning:

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

[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}`)
})

const express=require('express')
const bodyParser=require('body-parser')
const nodemailer=require('nodemailer')
const app=express()
//npm安装nodeEmailer googleapis
const{google}=require(“googleapis”);
const OAuth2=google.auth.OAuth2;
const oauth2Client=新OAuth2(
//客户
"*****",
//客户机密
"*****",
//重定向URL
"https://developers.google.com/oauthplayground"
);
oauth2Client.setCredentials({
刷新令牌:“******”
});
const accessToken=oauth2Client.getAccessToken()
app.use(bodyParser.json())
use(bodyParser.urlencoded({extended:false}))
app.post('/api/form',(req,res)=>{
nodeEmailer.createTestAccount((err,accounteé)=>{
常量htmlEmail=`
联系方式
  • 名称:${req.body.Name}
  • 电子邮件:${req.body.Email}
消息 ${req.body.message}

` 让transporter=nodeEmailer.createTransport({ 服务:“gmail”, 认证:{ 类型:“OAuth2”, 用户:“arne.pedersen。dev@gmail.com", clientId:“一些_id”, clientSecret:“一些秘密”, accessToken:accessToken } }); 让邮件选项={ 来自:阿恩·佩德森。dev@gmail.com', 致:阿恩·佩德森。dev@gmail.com', 回答:“阿恩·佩德森。dev@gmail.com', 主题:“新消息!”, 文本:req.body.message, html:htmlEmail } transporter.sendMail(邮件选项,(错误,信息)=>{ 如果(错误){ 返回console.log(错误) } console.log('已发送的消息:%s',info.Message) console.log('消息URL:%s',nodeEmailer.getTestMessageUrl(信息)) }) }) }) if(process.env.NODE_env==“生产”){ app.use(express.static('client/build')) 应用程序获取(“*”,(请求,请求)=>{ res.sendFile(path.resolve(_dirname,“client”,“build”,“index.html”)) }) } const PORT=process.env.PORT | | 3001 应用程序侦听(端口,()=>{ log(`Server侦听端口${port}`) })
试试这个。我和你有同样的问题,在搜索了几个小时的谷歌API代码后,我终于找到了答案! 希望这能帮助您解决代码中的问题。=)


您刚刚发布了您的客户端id和机密,您将希望立即撤销它们。这是一个离题的评论,我建议不要在SO上发布客户端机密。哦,很抱歉,您使用的是什么作用域以及在哪里定义它们?另外OAuth访问令牌的生命周期为1小时,我建议您从项目管理中获取凭据和令牌,您可以按照说明执行操作。
    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);
      }
    });