I'm building a Chrome extension that works with Gmail API and i need to send emails with local files (using their local file path) as attachments. I saw that with Gmail API, attachments need to be base64 encoded and then you can send them as a POST request. So i tried this:
// Here i convert the file to base64
const fileToBase64 = (filename, filepath) => {
return new Promise(resolve => {
var file = new File([filename], filepath);
var reader = new FileReader();
// Read file content on file loaded event
reader.onload = function(event) {
resolve(event.target.result);
};
// Convert data to base64
reader.readAsDataURL(file);
});
};
//Here i trigger the event, get the auth token and create the mail
$('#test').on('click', function(){
chrome.identity.getAuthToken({interactive: true}, function(token) {
console.log(token);
fileToBase64("pic4.jpg", "C:\Users\Davide\Downloads\pic4.jpg").then(result => {
console.log(result);
var splittedResult = result.split('base64,')[1];
var mail = [
'Content-Type: multipart/mixed; boundary="foo_bar_baz"\r\n',
'MIME-Version: 1.0\r\n',
'From: address1@gmail.com\r\n',
'To: address2@gmail.com\r\n',
'Subject: Subject Text\r\n\r\n',
'--foo_bar_baz\r\n',
'Content-Type: text/plain; charset="UTF-8"\r\n',
'MIME-Version: 1.0\r\n',
'Content-Transfer-Encoding: 7bit\r\n\r\n',
'The actual message text goes here\r\n\r\n',
'--foo_bar_baz\r\n',
'Content-Type: image/jpeg\r\n',
'MIME-Version: 1.0\r\n',
'Content-Transfer-Encoding: base64\r\n',
'Content-Disposition: attachment; filename="pic4.jpg"\r\n\r\n',
//base64 splitted result of previous function
splittedResult, '\r\n\r\n',
'--foo_bar_baz--'
].join('');
// Here i send the mail
$.ajax({
type: "POST",
url: "https://www.googleapis.com/upload/gmail/v1/users/me/messages/send?uploadType=multipart",
contentType: "message/rfc822",
beforeSend: function(xhr, settings) {
xhr.setRequestHeader('Authorization','Bearer '+ token );
},
data: mail
});
});
Result: i receive a mail at the destination address ( i receive also a copy to the source address, idk why) but the mail contains an empty attachment with the filename i've chosen (pic4.jpg) (cannot open it).
It seems the error to be in the base64 encoding from the absolute path, is there a way to fix or another way to do this?