繁体   English   中英

如何使用Gmail API和Javascript发送带有本地附件的电子邮件?

[英]How to send emails with Local Attachments using Gmail API and Javascript?

我正在构建一个可与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编码,是否有解决方法或另一种方法?

您可以使用XMLHttpRequest()。open()从本地路径打开文件,以将其传递给reader.readAsDataURL()。

请参阅示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM