I am making a request to the User.messages endpoint. All objects returned (the emails) have a mimeType property which I\'m struggling to understand.
More specificall
Based on the Tholle idea, I've completed his script to extract Gmail body and attachments.
First of all, you should fetch any gmail-message object and then parse it. You can fetch any gmail-message with this code:
const {google} = require('googleapis')
// do your authenticatoin here
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirectTo)
const gmail = google.gmail({ version: 'v1', auth: oAuth2Client })
const response = await this.gmail.users.messages.get({
auth: oAuth2Client,
userId: 'me',
id: messageId,
format: 'full'
})
const message_obj = response.data
Main Script:
function parser(response) {
function decode(input) {
const text = new Buffer.from(input, 'base64').toString('ascii')
return decodeURIComponent(escape(text))
}
function decode_alternative(input) {
// this way does not escape special "B" characters
// const text = Buffer.from(input, 'base64').toString('ascii')
// return decodeURIComponent(escape(text))
return base64.decode(input.replace(/-/g, '+').replace(/_/g, '/'))
}
const result = {
text: '',
html: '',
attachments: []
}
let parts = [response.payload]
while (parts.length) {
let part = parts.shift()
if (part.parts)
parts = parts.concat(part.parts)
if (part.mimeType === 'text/plain')
result.text = decode(part.body.data)
if (part.mimeType === 'text/html')
result.html = decode(part.body.data)
if (part.body.attachmentId) {
result.attachments.push({
'partId': part.partId,
'mimeType': part.mimeType,
'filename': part.filename,
'body': part.body
})
}
}
return result
}
Sample Data and response:
const with_multi_type_attachments = {
"id": "16c624e85dfd9883",
"threadId": "16c62397458f34b1",
"labelIds": [],
"snippet": "This is body. Inline-attachments my-custom-link my-custom-email-address Emoji: