【问题标题】:JavaScript - Gmail API - Send email with attachmentJavaScript - Gmail API - 发送带有附件的电子邮件
【发布时间】:2016-09-22 01:57:58
【问题描述】:

我已经找了好几个星期了。我只是希望能够发送一封带有附件的电子邮件。

我已经能够发送电子邮件、文本和 html。

我可以将文件上传到谷歌驱动器。

我以为知道这两件事可以让我达到最终目标,但我终生无法通过 gmail api 发送附件。

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

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

非常感谢任何指针。

【问题讨论】:

  • 看起来附件还没有被合并到 js 库中但是没有理由你不能手动调用端点..
  • 我花了整整一夜的时间从他们的文档中找出 gmail api,然后切换到 amazon ses,它就像节点邮件程序的魅力一样。
  • @PootieTang -- 你能详细说明“没有理由你不能手动调用端点”
  • 库所做的就是向它们的端点发出 AJAX 请求,编写一些 ajax 来调用端点

标签: javascript email-attachments gmail-api


【解决方案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');
    }
});

【讨论】:

    猜你喜欢
    • 2017-07-24
    • 2015-10-25
    • 2014-12-11
    • 2019-05-22
    • 2019-11-25
    • 2020-03-28
    • 2015-04-16
    • 2016-07-19
    • 2016-09-28
    相关资源
    最近更新 更多