Node.js sendmail()上的nodeEmailer w谷歌邮件服务帐户错误

Node.js sendmail()上的nodeEmailer w谷歌邮件服务帐户错误,node.js,firebase,google-cloud-functions,gmail-api,nodemailer,Node.js,Firebase,Google Cloud Functions,Gmail Api,Nodemailer,我正在尝试从Firebase函数发送电子邮件,此时我可以获取jwt客户端、授权iy、获取令牌并创建一个NodeEmailer transporter。 但是尝试使用transporter.sendmail()时,我得到一个错误: info: { Error: Invalid status code 401 at ClientRequest.req.on.res (/Users/yves/Developments/WIP/VUE.JS-vcli-3-beta/le-choro-de

我正在尝试从Firebase函数发送电子邮件,此时我可以获取jwt客户端、授权iy、获取令牌并创建一个NodeEmailer transporter。 但是尝试使用transporter.sendmail()时,我得到一个错误:

info: { Error: Invalid status code 401
        at ClientRequest.req.on.res (/Users/yves/Developments/WIP/VUE.JS-vcli-3-beta/le-choro-des-charentes/functions/node_modules/nodemailer/lib/fetch/index.js:221:23)
        at emitOne (events.js:116:13)
        at ClientRequest.emit (events.js:211:7)
        at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:551:21)
        at HTTPParser.parserOnHeadersComplete (_http_common.js:117:23)
        at TLSSocket.socketOnData (_http_client.js:440:20)
        at emitOne (events.js:116:13)
        at TLSSocket.emit (events.js:211:7)
        at addChunk (_stream_readable.js:263:12)
        at readableAddChunk (_stream_readable.js:250:11)
      type: 'FETCH',
      sourceUrl: 'https://accounts.google.com/o/oauth2/token',
      code: 'EAUTH',
      command: 'AUTH XOAUTH2' }
在读了很多帖子(在这么多不同的上下文中的问答)后,我迷路了。。。我的感觉是这个错误可能与refresk令牌有关。。。但谁知道呢

这是我的函数(我插入了一些console.log来观察它的进展…,所有的环境变量都设置为w functions.config()):

  • jwt客户端正常吗?我想可以静坐了
  • 代币可以吗?id_标记:未定义并刷新_标记:“jwt占位符”
  • 此无效状态代码401的含义是什么
    谢谢你的反馈。我离启动和运行它不远了,但这是经过漫长的GMail服务帐户认证后的最后一个问题

    我想在你的无记名代币过期后发布它并没有什么害处,但请检查你的其他私人数据,如项目ID,不会出现在问题中。当您使用脚本/请求进行签名时,是否可以检查脚本/请求是否有效?比较gcloud和您在中创建的JWT。
        const functions = require('firebase-functions');
        const admin = require('firebase-admin');
        admin.initializeApp();
    
        const { google } = require('googleapis')
        const nodemailer = require('nodemailer')
    
        exports.sendContactEmailOAuth = functions.https.onRequest((req, res) => {
          const sender_email = 'john.doe@acme.com';
          const sender_msg = 'just a test to contact the site owner.'
          const email = 'contact@example.com'
    
          const jwtClient = new google.auth.JWT({
            email: functions.config().service_key.client_email,
            key: functions.config().service_key.private_key,
            scopes: ['https://mail.google.com/']
            }
          )
    
          console.log('JWT Client: ', jwtClient)
    
          jwtClient.authorize((error, tokens) => {
            if (error) {
              console.log('NOT AUTHORIZE?: ', error)
              res.json({ success: false, error: error });
              return
            }
            console.log('AUTHORIZED tokens: ', tokens)
    
            var transporter = nodemailer.createTransport({
              host: "smtp.gmail.com",
              port: 465,
              secure: true,
              auth: {
                type: 'OAuth2',
                user: email,
                serviceClient: functions.config().service_key.client_id,
                privateKey: functions.config().service_key.private_key,
                accessToken: tokens.access_token,
                refreshToken: tokens.refresh_token,
                expires: tokens.expiry_date
              }
            });
    
            console.log('nodemailer transporter set...');
    
            const mailOptions = {
              from: 'An Example<' + sender_email + '>',
              to: email,
              subject: 'Apple and Banana',
              text: sender_msg,
              html: '<h1>Apple and Banana</h1><p>My html here</p>'
            };
    
            transporter.sendMail(mailOptions, (error, response) => {
              if (error) {
                console.log(error);
                res.end('error');
              } else {
                console.log("Message sent: " + response.message);
                res.end('sent');
              }
              transporter.close();
            });
          });
        });
    
        =====================
    
        info: User function triggered, starting execution
    
        info: JWT Client:  JWT {
          domain: null,
          _events: {},
          _eventsCount: 0,
          _maxListeners: undefined,
          transporter: DefaultTransporter {},
          credentials: { refresh_token: 'jwt-placeholder', expiry_date: 1 },
          certificateCache: null,
          certificateExpiry: null,
          refreshTokenPromises: Map {},
          _clientId: undefined,
          _clientSecret: undefined,
          redirectUri: undefined,
          authBaseUrl: undefined,
          tokenUrl: undefined,
          eagerRefreshThresholdMillis: 300000,
          email: 'postman@example-209605.iam.gserviceaccount.com',
          keyFile: undefined,
          key: '-----BEGIN PRIVATE KEY-----\nMIIEvAI........IZFwQg==\n-----END PRIVATE KEY-----\n',
          scopes: [ 'https://mail.google.com/' ],
          subject: undefined,
          additionalClaims: undefined }
    
        info: AUTHORIZED tokens:  { access_token: 'ya29.c.Elm6BYmTEQ6B82VWaAVx-9oXxX0ytUhgag-FJNPzFl1R9zEeeQQsGuMB5XnMrnbRRZBQuJkprvW1E_Sh8spyEmbd4iwAXbaj2Ou9vcww',
          token_type: 'Bearer',
          expiry_date: 1526217245000,
          id_token: undefined,
          refresh_token: 'jwt-placeholder' }
    
        info: nodemailer transporter set...
    
            info: { Error: Invalid status code 401
                at ClientRequest.req.on.res (/Users/myself/Developments/myapp/functions/node_modules/nodemailer/lib/fetch/index.js:221:23)
                at emitOne (events.js:116:13)
                at ClientRequest.emit (events.js:211:7)
                at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:551:21)
                at HTTPParser.parserOnHeadersComplete (_http_common.js:117:23)
                at TLSSocket.socketOnData (_http_client.js:440:20)
                at emitOne (events.js:116:13)
                at TLSSocket.emit (events.js:211:7)
                at addChunk (_stream_readable.js:263:12)
                at readableAddChunk (_stream_readable.js:250:11)
              type: 'FETCH',
              sourceUrl: 'https://accounts.google.com/o/oauth2/token',
              code: 'EAUTH',
              command: 'AUTH XOAUTH2' }