节点编辑器与sendmail上的Google Mail Service帐户错误()

时间:2018-05-13 12:41:35

标签: node.js firebase google-cloud-functions gmail-api nodemailer

我正在尝试从Firebase函数发送电子邮件,此时我可以获取jwt客户端,授权iy,获取令牌并创建nodemailer传输器。 但是尝试使用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' }

在阅读了很多帖子后(Q& A在很多不同的背景下)我迷失了......我的感觉是这个错误可能与刷新令牌有关......但谁知道呢?

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

    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' }
  1. jwt客户端好吗?我想坐的是授权的。
  2. 令牌好吗? id_token:undefined和refresh_token:'jwt-placeholder'?
  3. 这个无效状态代码401的含义是什么?
  4. 感谢您的反馈。我距离启动和运行并不远,但这是经过长期的GMail服务帐户身份验证之后的最后一个问题。

0 个答案:

没有答案