When I send emails using gapi, the receiver receives them correctly. However, when I check my "Sent" box, the emails appear as Chinese gibberish characters like in this image.
This issue only occurs when using non-gmail applications. If I view the Sent box in gmail, everything looks fine. But when I use Outlook or my Android's default Mail app connected to my gmail account, the content is completely messed up. It seems to be an encoding problem that Gmail can handle but other apps cannot.
Here's the code snippet I'm using to send emails:
async sendMail(email, files) {
//create cc and bcc string if needed
let ccStr = `Cc: ${email.cc}\r\n`
let bccStr = `Bcc: ${email.bcc}\r\n`
//create attachment if needed
let attachStr = await this.createAttachmentStr(files)
attachStr = `${attachStr}\r\n\r\n`
//create the message
let message = 'Content-Type: multipart/mixed; boundary="#split-part#"\r\n' +
'MIME-Version: 1.0\r\n' +
`To: ${email.to}\r\n` +
`From: ${email.from}\r\n` +
ccStr +
bccStr +
`Subject: ${email.subject}\r\n\r\n` +
'--#split-part#\r\n' +
'Content-Type: text/html; charset="UTF-8"\r\n' +
'MIME-Version: 1.0\r\n' +
'Content-Transfer-Encoding: base64\r\n\r\n' +
`${email.message}\r\n\r\n` +
`${attachStr}` +
'--#split-part#--'
//base64url encode
const encodedMessage = btoa(unescape(encodeURIComponent(message))).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
//send to api
gapi.client["gmail"].users.messages.send({
'userId': 'me',
'resource': {
'raw': encodedMessage,
"payload": {
"mimeType": 'multipart/mixed'
},
'threadId': email.id
}
}).then(async response => {
//do some stuff after
})
}
The method used in there called createAttachmentStr based on a FileList:
createAttachmentStr(files: FileList): Promise<string> {
return new Promise<string>((resolve) => {
let attachStr = ""
//initialize counter
let count = 0
//loop through each file
if (files && files.length > 0) {
Array.from(files).forEach(async file => {
//convert file to datastrings
let dataStr = await this.readFileContent(file)
//get file info
let fileName = file.name
let contentType = file.type
//create message str
attachStr += '--#split-part#\r\n' +
`Content-Type: ${contentType}\r\n` +
'MIME-Version: 1.0\r\n' +
'Content-Transfer-Encoding: base64\r\n' +
`Content-Disposition: attachment; filename="${fileName}"\r\n\r\n` +
`${dataStr}\r\n\r\n`
//increase the counter
count++
if (count === files.length) {
resolve(attachStr);
}
});
}
else resolve("")
});
}
This issue occurs rarely and seems to be related to specific emails with certain attachments. I'm struggling to figure out what triggers it exactly. Any help would be greatly appreciated.