Google GMail API - users.messages.import()不在INBOX中为什么?

时间:2018-05-27 10:44:20

标签: gmail gmail-api google-apis-explorer

我使用GMAil API直接导入邮件 当我查看GMail用户帐户(浏览器GMail应用程序)时,我可以在所有邮件中看到收到的邮件,但不能在INBOX中收到

Google GMail API声明:Users.messages.import()

  

仅将邮件导入此用户的邮箱,标准电子邮件传送扫描和分类类似于通过SMTP接收。不发送消息

由于消息在那里,我无法从Mail.app(OSX)或Outlook(MS)获取它,因为它不被视为新消息......是真的吗?无论如何要解决这个问题?

以下是我用来导入新邮件的功能

        unction gMailInserMessage (sender_name, sender_email, msg_text) {

      // Create a new JWT client using the key file downloaded from the Google Developer Console
      const jwtClient = new google.auth.JWT(
        postoffice_key.client_email,
        null,
        postoffice_key.private_key,
        _.values(config_key.scopes.postoffice),
        config_key.contact_email // subject (or sub) impersonated user
      );

      return jwtClient.authorize().then(tokens => {
          // Obtain a new gmail client, making sure we pass along the auth client
          const gmail = google.gmail({
            version: 'v1',
            auth: jwtClient
           });

          const subject = ' CONTACT ';
          const utf8Subject = `=?utf-8?B?${Buffer.from(subject).toString('base64')}?=`;
          const messageParts = [
            'From: ' + sender_name + '<' + sender_email + '>',
            'To: Contact Box <' + config_key.contact_email + '>',
            'Content-Type: text/html; charset=utf-8',
            `Subject: ${utf8Subject}`,
            '',
            'A new contact message just to say hello.',
            'So... <b>Hello!</b>  ❤️'
          ];
          const message = messageParts.join('\n');

          // The body needs to be base64url encoded.
          const encodedMessage = Buffer.from(message)
          .toString('base64')
          .replace(/\+/g, '-')
          .replace(/\//g, '_')
          .replace(/=+$/, '');

          //Make an authorized request to import a User Messages
          return gmail.users.messages.import({
            userId: 'me',
            resource: {
              raw: encodedMessage
            }
          });
      }).then(res => {
        // console.log('RES: ', res)
        return res.data;
      });
    }

以下是我从requets获得的回复

                RES:  { status: 200,
              statusText: 'OK',
              headers: 
               { 'cache-control': 'no-cache, no-store, max-age=0, must-revalidate',
                 pragma: 'no-cache',
                 expires: 'Mon, 01 Jan 1990 00:00:00 GMT',
                 date: 'Sun, 27 May 2018 10:00:12 GMT',
                 etag: '"Mr5Glppow16hK9x9KiNoxDVbWS4/98vlvSafvJVr4JD8evQ2SHoRCuQ"',
                 vary: 'Origin, X-Origin',
                 'content-type': 'application/json; charset=UTF-8',
                 'x-content-type-options': 'nosniff',
                 'x-frame-options': 'SAMEORIGIN',
                 'x-xss-protection': '1; mode=block',
                 server: 'GSE',
                 'alt-svc': 'hq=":443"; ma=2592000; quic=51303433; quic=51303432; quic=51303431; quic=51303339; quic=51303335,quic=":443"; ma=2592000; v="43,42,41,39,35"',
                 connection: 'close',
                 'transfer-encoding': 'chunked' },
              config: 
               { adapter: [Function: httpAdapter],
                 transformRequest: { '0': [Function: transformRequest] },
                 transformResponse: { '0': [Function: transformResponse] },
                 timeout: 0,
                 xsrfCookieName: 'XSRF-TOKEN',
                 xsrfHeaderName: 'X-XSRF-TOKEN',
                 maxContentLength: 2147483648,
                 validateStatus: [Function],
                 headers: 
                  { Accept: 'application/json, text/plain, */*',
                    'Content-Type': 'application/json;charset=utf-8',
                    'Accept-Encoding': 'gzip',
                    'User-Agent': 'google-api-nodejs-client/31.0.2 (gzip)',
                    Authorization: 'Bearer ya29.GoEByAXKR5aJgJanVZebkHwurMcOn6FB4ymK9BZqmi_0K0uMPK_1AJAL-EQa0ajz1OBDoJE1cWAyRzprOYbDnJrnpusrPfFSL7HuBmMqXFULxEKECedOb5pKwkTFA9CffIZS1Fg1uwuGcsgUqO98XOkYeRh9ul7icvBpuzUgaML0SVJN',
                    'Content-Length': 397 },
                 method: 'post',
                 url: 'https://www.googleapis.com/gmail/v1/users/me/messages/import',
                 paramsSerializer: [Function],
                 data: '{"raw":"RnJvbTogTW1lIElzYWJlbGxlIER1Zm91ciA8ZHVmb3VyaXNhYmVsbGVAb3JhbmdlLmZyPgpUbzogQ29udGFjdCBCb3ggPHl2ZXNkdWZvdXJAbGVjaG9yb2Rlc2NoYXJlbnRlcy5vcmc-CkNvbnRlbnQtVHlwZTogdGV4dC9odG1sOyBjaGFyc2V0PXV0Zi04Ck1JTUUtVmVyc2lvbjogMS4wClN1YmplY3Q6ID0_dXRmLTg_Qj84SitrbUNCRFQwNVVRVU5VSVBDZnBKZz0_PQoKVGhpcyBpcyBhIE5FVyBORVcgbWVzc2FnZSBqdXN0IHRvIHNheSBoZWxsby4KU28uLi4gPGI-SGVsbG8hPC9iPiAg8J-kmOKdpO-4j_CfmI4"}',
                 params: { internalDateSource: 'dateHeader' } },

1 个答案:

答案 0 :(得分:1)

解决了在尝试使用Firebase功能处理网站联系表单时引发的所有问题。

1 - 使用GCP,在我的Firebase项目中,我创建了一个名为“postoffice”的服务帐户,使用域范围委派,将JSON格式的凭据下载到functions / postoffice-key.json中 2 - 我为项目启用了GMail API 3 - 我在另一个函数/ config-key.json

中处理范围和电子邮件地址

4-在我的GSuite管理控制台中(安全性&gt;高级设置&gt;管理API客户端访问,我使用授权范围从postoffice-key.json文件添加了clientId

5 - 我写了一个新的Firebase HTTPS功能: newContactMessage()

    const functions = require('firebase-functions');
    const admin = require('firebase-admin');
    admin.initializeApp();

    const { google } = require('googleapis');
    const path = require('path');
    const _ = require('lodash');

    var Buffer = require('buffer/').Buffer  // note: the trailing slash is important!

    // KEY FILES
    const postoffice_key = require('./postoffice-key.json');
    const config_key = require('./config-key.json');

    function gMailInsertContactMessage (sender_name, sender_email, msg_text) {

      // Create a new JWT client using the key file downloaded from the Google Developer Console
      const jwtClient = new google.auth.JWT(
        postoffice_key.client_email,
        null,
        postoffice_key.private_key,
        _.values(config_key.scopes.postoffice),
        config_key.admin_email // subject (or sub) impersonated user
      );

      return jwtClient.authorize().then(tokens => {
          // Obtain a new gmail client, making sure we pass along the auth client
          const gmail = google.gmail({
            version: 'v1',
            auth: jwtClient
           });

          const subject = ' CONTACT ';
          const utf8Subject = `=?utf-8?B?${Buffer.from(subject).toString('base64')}?=`;
          const messageParts = [
            'From: "Administrator" <' + config_key.admin_email + '>',
            'To: "Contact Box" <' + config_key.contact_email + '>',
            'Reply-To: "' + sender_name + '" <' + sender_email + '>',
            'Content-Type: text/html; charset=utf-8',
            'MIME-Version: 1.0',
            `Subject: ${utf8Subject}`,
            '',
            '<h2>MESSAGE</h2>',
            '<p>' + msg_text + '</p>'
          ];
          const message = messageParts.join('\n');

          // The body needs to be base64url encoded.
          const encodedMessage = Buffer.from(message)
          .toString('base64')
          .replace(/\+/g, '-')
          .replace(/\//g, '_')
          .replace(/=+$/, '');

          //Make an authorized request to import a User Messages
          return gmail.users.messages.send({
            userId: 'me',
            resource: {
              raw: encodedMessage
            }
          });
      }).then(res => {
        // console.log('RES: ', res)
        return res.data;
      });
    }

    // FIREBASE HTTP FUNCTIONS ==================

    exports.newContactMessage = functions.https.onRequest((req, res) => {
      const sender_name = 'Mrs Jenny Doe'
      const sender_email = 'jenny.doe@example.com'
      const sender_msg = 'Hello, how are you overthere ?'
      gMailInsertContactMessage(sender_name, sender_email, sender_msg).then((res) => {
        return { status: 200, infos: res };
      }, error => {
        return {status: error.status, infos: error.message};
      }).then(response => {
        return res.send(response);
      }).catch(console.error);
    });

测试请求:

curl -v https://us-central1-myproject.cloudfunctions.net/newContactMessage

Firebase功能返回:

{"status":200,"infos"
{"id":"163a5738080e3ee9","threadId":"163a5738080e3ee9","labelIds":["SENT"]}}

在我的计算机上的Mail.app中,我可以看到From:是项目所有者(管理员)To:是联系人框(contact@mysite.org和回复:是联系表格发件人电子邮件) ...容易回复..! 和消息内容!

希望这有帮助......(我应该编辑问题标题吗?)