JavaScript - Gmail API - 发送带附件的电子邮件

时间:2016-05-24 17:52:41

标签: javascript email-attachments gmail-api

我一直在寻找这个星期。我只是想发送一封带有附件的电子邮件。

我已经能够发送电子邮件,短信和HTML。

我可以将文档上传到Google云端硬盘。

我认为知道这两件事会让我达到我的最终目标,但我不能为我的生活获得通过gmail api发送的附件。

这个问题很可能已经在堆栈溢出,但我还没有看到任何以 javascript 作为语言的帖子。并且那些没有解决发送带附件的电子邮件的问题。

我不在乎它是通过cors还是通过gapi.client,我只是需要它才能工作。

任何指针都非常感激。

1 个答案:

答案 0 :(得分:1)

这是我迄今取得的成就。我正在使用gapi客户端库。

首先,您必须正确构建电子邮件,这是我的工作示例,请注意,在任何部分之间需要空行。您可以将所有部分添加到数组中,并使用your_array.join('\r\n')构建电子邮件。

Content-Type: multipart/mixed; boundary="your_boundary"
MIME-Version: 1.0
From: person1@gmail.com
To: person2@gmail.com
Subject: Test
Reply-To: person1@gmail.com
Date: Wed Jan 04 2017 10:47:11 GMT-0500 (EST)

--your_boundary
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: quoted-printable

<p>Boundary, multi attachs<br />
<em><strong>--<br />
With Regards</strong></em></p>

--your_boundary
Content-Type: image/png
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="sort_asc.png"

YOUR_BASE64_ENCODED_DATA

--your_boundary
Content-Type: image/png
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="sort_both.png"

YOUR_BASE64_ENCODED_DATA

--your_boundary
Content-Type: image/png
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="sort_desc.png"

YOUR_BASE64_ENCODED_DATA

--your_boundary--

然后我使用gapi的客户端发送电子邮件; sendMessage是gapi在线文档提供的功能。在发送电子邮件之前,您需要 Base64URL 对您的电子邮件进行编码。我从这里得到了编码库:https://www.npmjs.com/package/js-base64

sendMessage = function(userId, email, callback) {
     var request = gapi.client.gmail.users.messages.send({
        'userId': userId,
        'resource': {
            'raw': email
        }
    });

    request.execute(callback);
}

sendMessage('me', Base64.encodeURI(email), function(resp) {
    if(resp.labelIds && resp.labelIds.indexOf('SENT') > -1) {
        console.log('Your email has been sent.');
    }else {
        console.log('Something went wrong');
    }
});