Reputation: 1
I've been struggling with reading messages from Gmail API.
I can get the body of every mail using mail.Payload.Parts[0].Body.Data, which contains the message body in base64.
The thing is that when the mail I'm retrieving has an attachment, parts[0] MimeType is "multipart/alternative", and its body has only null fields.
How can I get the mail body if it has attachments? The code velow works well for mails without attachment, but gets nothing for mails with attachment
Please advice. Thanks!
function getRecentEmail(auth) {
const gmail = google.gmail({version: 'v1', auth});
// Only get the recent email - 'maxResults' parameter
gmail.users.messages.list({auth: auth, userId: 'me', maxResults: 13 ,}, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
// Get the message id which we will need to retreive tha actual message next.
var message_id = response['data']['messages'][0]['id'];
// Retreive the actual message using the message id
gmail.users.messages.get({auth: auth, userId: 'me', 'id': message_id}, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
// console.log(response['data']);
console.log('xxxxxxxxxxxxxxxxxxxxxxxxx');
console.log(data.payload.parts);
console.log(data.payload);
message_raw = response.data.payload.parts[0].body.data;
data = message_raw;
buff = new Buffer.from(data, 'base64');
text = buff.toString();
console.log(text);
});
});
}
/*Below is the console output.
The part [0].body returns null while part [1].body has the attachment. Cannot see the email message part anywhere. Below is the console output.
{
partId: '0',
mimeType: 'multipart/alternative',
filename: '',
headers: [ [Object] ],
body: { size: 0 },
parts: [ [Object], [Object] ]
},
{
partId: '1',
mimeType: 'image/jpeg',
filename: '3.JPG',
headers: [ [Object], [Object], [Object], [Object], [Object] ],
body: {
attachmentId: 'ANGjdJ80EeMqROfRj4fMz751dKoqD4OW1rW6qu483Fo2vZw1FG2YT7AOJcV
UsnO5cbeHoSWiftO5Z_OAtPghlftkLdpMTUFzGSYgcJ3fLR2nnNoMbvJxl-BCsFCPndRlL2G5-OUKmO0
mhO8knKAYtDrdAcaMb_9lbQcG379jtXIYQEpnKADEbLFy1i_ZAmyAg3prC-P0QNBQE-FTi4x26qRUeTM
hv8quTt9LMOhwnA',
size: 44199
}
}
*/
Upvotes: 0
Views: 722