我正在构建一个可与Gmail API一起使用的Chrome扩展程序,我需要发送包含本地文件(使用其本地文件路径)作为附件的电子邮件。 我看到,使用Gmail API,附件需要使用base64编码,然后您可以将其作为POST请求发送。所以我尝试了这个:
// 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
});
});
结果:我在目标地址收到一封邮件(我也收到到源地址的副本,为什么是idk),但是该邮件包含一个空附件,其文件名是我选择的(pic4.jpg)(无法打开) )。
似乎绝对路径中的base64编码中存在错误,是否有解决方法或另一种方法?