简体   繁体   English

Gmail API-使用Java脚本解析邮件内容(Base64解码?)

[英]Gmail API - Parse message content (Base64 decoding?) with Javascript

I'm trying to use the Gmail API to get a user's email, grab the message subject and body, and then display it on a webpage. 我正在尝试使用Gmail API来获取用户的电子邮件,获取邮件的主题和正文,然后将其显示在网页上。 I'll be doing other stuff with it, but this is the part that I am having difficulty with. 我将用它来做其他事情,但这是我遇到的困难。 I am using Angular.js. 我正在使用Angular.js。

Here is my API call: 这是我的API调用:

function makeApiCall() {
  gapi.client.load('gmail', 'v1', function() {
    var request = gapi.client.gmail.users.messages.list({
      labelIds: ['INBOX']
    });
    request.execute(function(resp) {
      var content = document.getElementById("message-list");
      angular.forEach(resp, function(message) {
        var email = gapi.client.gmail.users.messages.get({'id': message.id});
        // var raw = email.payload.parts;
        // console.log(raw);
        content.innerHTML += JSON.stringify(email) + "<br>";
      })
    });
  });
}

So gapi.client.gmail.users.messages.list returns an array of my messages, with their ID numbers. 因此, gapi.client.gmail.users.messages.list返回我的消息的数组以及它们的ID号。 That is working. 可以了

The call to gapi.client.gmail.users.messages.get({<specific message ID>}) outputs this - {"B":{"method":"gmail.users.messages.get","rpcParams":{},"transport":{"name":"googleapis"}}} . 调用gapi.client.gmail.users.messages.get({<specific message ID>})输出以下内容- {"B":{"method":"gmail.users.messages.get","rpcParams":{},"transport":{"name":"googleapis"}}}

Not sure what that is, but trying to get the message payload ( email.payload.parts ), results in undefined . 不知道这是什么,但是尝试获取消息有效负载( email.payload.parts ),结果为undefined So, how can I get the message content? 那么,如何获得消息内容?

Also, I would assume that if I can get the message contents, I would then have to Base64 decode the contents to get some English out of it. 另外,我假设如果我可以获取消息内容,那么我将不得不对Base64进行解码以从中获取一些英语信息。 Any suggestions for that would be of great help also. 对此的任何建议也将有很大帮助。 I've found this: https://github.com/kvz/phpjs , but since I'm not sure how to go about getting the message contents so that I can try and decode them, so not sure if that php.js is of an help in that regard. 我发现了这一点: https : //github.com/kvz/phpjs ,但是由于我不确定如何获取消息内容以便我可以尝试对其进行解码,所以不确定php.js是否在这方面有帮助。

Regarding the Base64 decoding, you can use 关于Base64解码,您可以使用

atob(dataToDecode)

For Gmail, you'll also want to replace some characters: 对于Gmail,您还需要替换一些字符:

atob( dataToDecode.replace(/-/g, '+').replace(/_/g, '/') ); 

The above function is available to you in JavaScript (see ref ). 您可以在JavaScript中使用上述功能(请参阅参考资料 )。 I use it myself to decode the Gmail messages. 我自己使用它来解码Gmail邮件。 No need to install extra stuff. 无需安装其他东西。 As an interesting tangent, if you want to encode your message to Base64, use btoa. 作为有趣的切线,如果要将消息编码为Base64,请使用btoa。

Now, for accessing your message payload, you can write a function: 现在,为了访问消息有效负载,您可以编写一个函数:

var extractField = function(json, fieldName) {
  return json.payload.headers.filter(function(header) {
    return header.name === fieldName;
  })[0].value;
};
var date = extractField(response, "Date");
var subject = extractField(response, "Subject");

referenced from my previous SO Question and 从我之前的SO问题中引用,并且

var part = message.parts.filter(function(part) {
  return part.mimeType == 'text/html';
});
var html = atob(part.body.data.replace(/-/g, '+').replace(/_/g, '/'));

Depending on what your emails look like (single text/plain part? multipart with text/html? attachments, etc?) you may or may not have any "parts" in your email.payload and instead you'll have what you're looking for in "email.payload.body.data" (for single-part messages). 根据您的电子邮件的外观(单个文本/纯文本部分;包含文本/ html的多部分文本?等等),您在email.payload中可能有也可能没有任何“部分”,而您会得到在“ email.payload.body.data”中查找(用于单部分邮件)。 This is all assuming you're doing a message.get with the default format ("full"). 所有这些都假设您正在使用默认格式(“完整”)执行message.get。 If you instead want to get the entire email in the message.raw field and deal with it in email libraries for your language you can call message.get(format=raw). 如果您想在message.raw字段中获取整个电子邮件,并在电子邮件库中以您的语言进行处理,则可以调用message.get(format = raw)。

For more info check out the "body" and "parts[]" field documentation for "Message" at https://developers.google.com/gmail/api/v1/reference/users/messages 有关更多信息,请访问https://developers.google.com/gmail/api/v1/reference/users/messages中的 “消息”的“正文”和“部件[]”字段文档。

Ah! 啊! I figured it out. 我想到了。 parts is an array, so I should have been calling it like: gapi.client.gmail.users.messages.get({'id': <message ID>}).payload.parts[0].body.data parts是一个数组,所以我应该这样称呼它: gapi.client.gmail.users.messages.get({'id': <message ID>}).payload.parts[0].body.data

Now my problem is decoding the emails, which is proving successful in plain text emails, but failing in emails from non-personal locations (businesses, social media update emails, etc.). 现在,我的问题是对电子邮件进行解码,这在纯文本电子邮件中被证明是成功的,但是在非个人位置(企业,社交媒体更新电子邮件等)中的电子邮件却失败了。 But I'll make a new question to get answers for that. 但是,我将提出一个新问题以获取答案。

You need to search where the body for a given mime type is, I have written a recursive function for that: 您需要搜索给定mime类型的正文的位置,为此我编写了一个递归函数:

function searchBodyRec(payload, mimeType){
    if (payload.body && payload.body.size && payload.mimeType === mimeType) {
        return payload.body.data;
    } else if (payload.parts && payload.parts.length) {
        return payload.parts.flatMap(function(part){
            return searchBodyRec(part, mimeType);
        }).filter(function(body){
            return body;
        });
    }
}

So now you can call 所以现在你可以打电话

var encodedBody = searchBodyRec(this.message.payload, 'text/plain');

See the flatMap method up there? 在那里看到flatMap方法了吗? Classic FP method missing in js, here is how to add it (or you can use lodash.js, or underscore.js if you don't want to mess with the native objects) js中缺少的经典FP方法,这是添加方法(或者您可以使用lodash.js或underscore.js,如果您不想弄乱原生对象)

Array.prototype.flatMap = function(lambda) { 
    return Array.prototype.concat.apply([], this.map(lambda)); 
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM