【发布时间】:2019-11-25 09:58:00
【问题描述】:
我正在构建一个与 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
});
});
结果:我在目标地址收到一封邮件(我还收到一份到源地址的副本,我知道为什么)但邮件包含一个带有我选择的文件名的空附件(pic4.jpg)(无法打开它)。
似乎错误出在绝对路径的base64编码中,有没有办法修复或另一种方法来做到这一点?
【问题讨论】:
-
@Diodeus-JamesMacFarlane 尝试拆分 base64 网址,但它不起作用,结果相同..
-
这是 FileReader 文档中提供的信息:如果不首先删除 Base64 编码数据之前的 Data-URL 声明,则无法将 blob 的结果直接解码为 Base64。要仅检索 Base64 编码的字符串,请首先从结果中删除 data:*/*;base64。 developer.mozilla.org/en-US/docs/Web/API/FileReader/…
-
@ziganotschka 已经尝试过,将字符串从“base64”中拆分出来,但没有任何改变。还尝试为图像添加相对路径,但它不起作用。
-
@ziganotschka 是的,错误就在那里:我用 HTML 制作了一个输入文件表单,一切正常。我现在应该找到一种方法来从本地路径创建文件,而无需使用输入表单(出于安全原因可能无法实现)或其他上传整个附件的方法。
标签: javascript base64 gmail-api mime-types email-attachments