Gmail API - 使用 Javascript 解析邮件内容(Base64 解码?)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24745006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Gmail API - Parse message content (Base64 decoding?) with Javascript
提问by artis3n
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. I'll be doing other stuff with it, but this is the part that I am having difficulty with. I am using Angular.js.
我正在尝试使用 Gmail API 来获取用户的电子邮件,获取邮件主题和正文,然后将其显示在网页上。我会用它做其他事情,但这是我遇到困难的部分。我正在使用 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. That is working.
所以gapi.client.gmail.users.messages.list
返回一组我的消息,以及它们的 ID 号。那是有效的。
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
. So, how can I get the message content?
不确定那是什么,但尝试获取消息有效负载 ( email.payload.parts
),结果是undefined
. 那么,如何获取消息内容呢?
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. 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.
另外,我会假设如果我可以获取消息内容,那么我将不得不对内容进行 Base64 解码以从中获取一些英语。对此的任何建议也会有很大帮助。我发现了这个:https://github.com/kvz/phpjs,但由于我不确定如何获取消息内容以便我可以尝试解码它们,所以不确定那个 php.js在这方面是有帮助的。
采纳答案by Eric D
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). This is all assuming you're doing a message.get with the default format ("full"). 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).
根据您的电子邮件的外观(单个文本/纯文本?多部分与文本/html?附件等?),您的 email.payload 中可能有也可能没有任何“部分”,而您将拥有自己的内容在“email.payload.body.data”中查找(用于单部分消息)。这一切都假设您正在使用默认格式(“完整”)执行 message.get 。如果您想在 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 上的“Message”的“body”和“parts[]”字段文档
回答by FullStack
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). I use it myself to decode the Gmail messages. No need to install extra stuff. As an interesting tangent, if you want to encode your message to Base64, use btoa.
您可以在 JavaScript 中使用上述函数(请参阅参考资料)。我自己用它来解码 Gmail 邮件。无需安装额外的东西。有趣的是,如果您想将消息编码为 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 Questionand
引用自我之前的SO 问题和
var part = message.parts.filter(function(part) {
return part.mimeType == 'text/html';
});
var html = atob(part.body.data.replace(/-/g, '+').replace(/_/g, '/'));
回答by artis3n
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.
现在我的问题是解码电子邮件,这在纯文本电子邮件中证明是成功的,但在来自非个人位置(企业、社交媒体更新电子邮件等)的电子邮件中失败。但我会提出一个新问题以获得答案。
回答by standup75
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? 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)
看到上面的 flatMap 方法了吗?js 中缺少经典的 FP 方法,这里是如何添加它(或者,如果您不想弄乱原生对象,可以使用 lodash.js 或 underscore.js)
Array.prototype.flatMap = function(lambda) {
return Array.prototype.concat.apply([], this.map(lambda));
};