【问题标题】:Google GMail API - users.messages.import() not in INBOX Why?Google GMail API - users.messages.import() 不在收件箱中 为什么?
【发布时间】:2018-11-06 03:49:30
【问题描述】:

我正在使用 GMAil API 直接导入消息 当我查看 GMail 用户帐户(浏览器 GMail 应用程序)时,我可以看到在 All Mails 中收到的消息,但在 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;
      });
    }

这是我从请求中得到的回复

                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' } },

【问题讨论】:

  • 看来我需要添加 'MIME-Version: 1.0' 标头...在这种情况下,响应是:{"status":200,"infos":{"id": "163a1758e7d02ed2","threadId":"163a1758e7d02ed2","labelIds":["UNREAD","SENT","INBOX"]}}....
  • 但我既没有收到发件人姓名,也没有收到收件人姓名:即使使用“发件人:”+发件人名称+“”,“收件人:联系人框',... 为什么?
  • 是的......就是这样......我正在检查为什么 From: name 不显示(仅获取发件人电子邮件地址)与 To: 相同......
  • 现在就知道了...当显示名称包含空格字符时需要引用它会发布完整功能作为答案

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


【解决方案1】:

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

1 - 使用 GCP,在我的 Firebase 项目中,我创建了一个名为“邮局”的服务帐户,具有域范围授权,将 JSON 格式的凭据下载到函数/postoffice-key.json 2 - 我为项目启用了 GMail API 3 - 我在另一个函数/config-key.json 中处理范围和电子邮件地址

4- 在我的 GSuite 管理控制台(安全>高级设置>管理 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: 作为项目所有者 ( Administrator ) To: 作为联系人框 (contact@mysite.org 和 Reply-To: 作为联系表发件人电子邮件...容易回复..! 以及消息内容!

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

【讨论】:

    猜你喜欢
    • 2015-12-02
    • 2014-12-19
    • 2016-05-23
    • 2017-09-02
    • 2019-04-29
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多