第一部分代码适用于总大小为mb的附件。如果要使用允许的35 mb的限制,请在答案末尾检查编辑。
在Steve将我推向正确的方向(整个邮件必须在“原始”参数中)之后,我简单地尝试了Python API并查看了由此生成的邮件。
没有附件的邮件
Content-Type: text/plain; charset="UTF-8"MIME-Version: 1.0Content-Transfer-Encoding: 7bitto: receiver@gmail.comfrom: sender@gmail.comsubject: Subject TextThe actual message text goes here
带附件的邮件
Content-Type: multipart/mixed; boundary="foo_bar_baz"MIME-Version: 1.0to: receiver@gmail.comfrom: sender@gmail.comsubject: Subject Text--foo_bar_bazContent-Type: text/plain; charset="UTF-8"MIME-Version: 1.0Content-Transfer-Encoding: 7bitThe actual message text goes here--foo_bar_bazContent-Type: image/jpegMIME-Version: 1.0Content-Transfer-Encoding: base64Content-Disposition: attachment; filename="example.jpg"{JPEG data}--foo_bar_baz--
因此,我只是围绕此代码编写了代码,并且效果很好!
var reader = new FileReader();reader.readAsDataURL(attachment);reader.onloadend = function (e) { // The relevant base64-encoding comes after "base64," var jpegData = e.target.result.split('base64,')[1]; var mail = [ 'Content-Type: multipart/mixed; boundary="foo_bar_baz"rn', 'MIME-Version: 1.0rn', 'to: receiver@gmail.comrn', 'from: sender@gmail.comrn', 'subject: Subject Textrnrn', '--foo_bar_bazrn', 'Content-Type: text/plain; charset="UTF-8"rn', 'MIME-Version: 1.0rn', 'Content-Transfer-Encoding: 7bitrnrn', 'The actual message text goes herernrn', '--foo_bar_bazrn', 'Content-Type: image/jpegrn', 'MIME-Version: 1.0rn', 'Content-Transfer-Encoding: base64rn', 'Content-Disposition: attachment; filename="example.jpg"rnrn', jpegData, 'rnrn', '--foo_bar_baz--' ].join(''); // The Gmail API requires url safe base64 // (replace '+' with '-', replace '/' with '_', remove trailing '=') mail = btoa(mail).replace(/+/g, '-').replace(///g, '_').replace(/=+$/, ''); $.ajax({ type: "POST", url: "https://www.googleapis.com/gmail/v1/users/me/messages/send", headers: { 'Authorization': 'Bearer ' + accessToken, 'Content-Type': 'application/json' }, data: JSON.stringify({ raw: mail }) });}
编辑
上面的代码有效,但是需要一些更改才能使用最大限制为35 mb。
以标题为 Mail with attachment的邮件 为例,更改后的ajax-request如下所示:
$.ajax({ type: "POST", url: "https://www.googleapis.com/gmail/v1/users/me/messages/send?uploadType=multipart", headers: { 'Authorization': 'Bearer ' + accessToken, 'Content-Type': 'message/rfc822' }, data: mail});
在
Content-Type现在
message/rfc822,而不是
application/json,网址已经得到了新的参数
uploadType=multipart,而且最重要的邮件不再是base64编码,但在提供
rfc822-format。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)