Reputation: 1518
Whenever I make a test request via API explorer (https://developers.google.com/apis-explorer/#p/gmail/v1/gmail.users.messages.get?) I get a payload that contains numerous body tags in the JSON output. I need to grab the body tag that represents the text of the message body and nothing else. How do I know, in each response, which body tag that is?
Upvotes: 3
Views: 3650
Reputation: 112897
You can check the mimeType
of the parts in the payload
for a part with type text/html
or text/plain
:
var response = {
"payload": {
"parts": [
{
"mimeType": "multipart/alternative",
"filename": "",
"headers": [
{
"name": "Content-Type",
"value": "multipart/alternative; boundary=001a1142e23c551e8e05200b4be0"
}
],
"body": {
"size": 0
},
"parts": [
{
"partId": "0.0",
"mimeType": "text/plain",
"filename": "",
"headers": [
{
"name": "Content-Type",
"value": "text/plain; charset=UTF-8"
}
],
"body": {
"size": 9,
"data": "V293IG1hbg0K"
}
},
{
"partId": "0.1",
"mimeType": "text/html",
"filename": "",
"headers": [
{
"name": "Content-Type",
"value": "text/html; charset=UTF-8"
}
],
"body": {
"size": 30,
"data": "PGRpdiBkaXI9Imx0ciI-V293IG1hbjwvZGl2Pg0K"
}
}
]
},
{
"partId": "1",
"mimeType": "image/jpeg",
"filename": "feelthebern.jpg",
"headers": [
{
"name": "Content-Type",
"value": "image/jpeg; name=\"feelthebern.jpg\""
},
{
"name": "Content-Disposition",
"value": "attachment; filename=\"feelthebern.jpg\""
},
{
"name": "Content-Transfer-Encoding",
"value": "base64"
},
{
"name": "X-Attachment-Id",
"value": "f_ieq3ev0i0"
}
],
"body": {
"attachmentId": "ANGjdJ_2xG3WOiLh6MbUdYy4vo2VhV2kOso5AyuJW3333rbmk8BIE1GJHIOXkNIVGiphP3fGe7iuIl_MGzXBGNGvNslwlz8hOkvJZg2DaasVZsdVFT_5JGvJOLefgaSL4hqKJgtzOZG9K1XSMrRQAtz2V0NX7puPdXDU4gvalSuMRGwBhr_oDSfx2xljHEbGG6I4VLeLZfrzGGKW7BF-GO_FUxzJR8SizRYqIhgZNA6PfRGyOhf1s7bAPNW3M9KqWRgaK07WTOYl7DzW4hpNBPA4jrl7tgsssExHpfviFL7yL52lxsmbsiLe81Z5UoM",
"size": 100446
}
}
]
}
};
function decode(string) {
return decodeURIComponent(escape(atob(string.replace(/\-/g, '+').replace(/\_/g, '/'))));
}
function getText(response) {
var result = '';
// In e.g. a plain text message, the payload is the only part.
var parts = [response.payload];
while (parts.length) {
var part = parts.shift();
if (part.parts) {
parts = parts.concat(part.parts);
}
if (part.mimeType === 'text/plain') {
// Continue to look for a 'text/html' part.
result = decode(part.body.data);
} else if (part.mimeType === 'text/html') {
// 'text/html' part found. No need to continue.
result = decode(part.body.data);
break;
}
}
return result;
}
var text = getText(response);
console.log(text);
Upvotes: 2
Reputation: 16394
They all are. A MIME multipart message contains multiple bodies. how to convert it to what you consider a "standard" representation depends. Sometimes the parts are alternatives (i. e. HTML vs. txt) and you can pick one. It could also be a file attachment, a signature, etc.
See https://en.wikipedia.org/wiki/MIME#Multipart_messages for details on the format.
Upvotes: 0