gmail - Google GMail API - users.messages.import() 不在收件箱中 为什么?

标签 gmail gmail-api google-apis-explorer

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

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

Imports a message into only this user's mailbox, with standard email delivery scanning and classification similar to receiving via SMTP. Does not send a message

由于邮件放在那儿,我无法从 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' } },

最佳答案

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

1 - 使用 GCP,在我的 Firebase 项目中,我创建了一个名为“postoffice”的服务帐户,具有域范围委派,将 JSON 格式的凭据下载到 functions/postoffice-key.json 2 - 我为项目启用了 GMail API 3 - 我在另一个 functions/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 中,我可以看到发件人:项目所有者(管理员)收件人:联系人框(contact@mysite.org 和回复:联系表发件人电子邮件...容易回复..! 以及消息内容!

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

关于gmail - Google GMail API - users.messages.import() 不在收件箱中 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50551326/

相关文章:

node.js - 使用服务帐户 key 列出来自谷歌驱动器的公开共享文件未获取公共(public)文件

php - 如何在 Gmail 中使用 Swiftmailer 设置 'FROM' 属性?

node.js - Node js 为 gmail 发送 session /日历邀请

gmail - Google Gmail 上下文小工具示例

java - 在没有用户交互的情况下发送电子邮件 - Android Studio

javascript - Nodejs Google Drive API 可共享链接

java - Log4j:无法使用 Log4j SMTP Appenders 发送邮件

python - 如何使用 Gmail API 在现有线程中创建草稿消息

javascript - 是否可以添加一个带有端口的pushEndpoint?

gmail-api - 400 错误。需要收件人地址。 JavaScript