【问题标题】:Send mail with attachment (PDF) using Gmail API使用 Gmail API 发送带有附件 (PDF) 的邮件
【发布时间】:2018-11-11 08:04:51
【问题描述】:

问题

所有数据都以文本格式发送,而不是作为附件的 PDF。

我的代码

var boundary = "__myapp__", nl = "\n";
// var attach = data.toString("base64");
var fileName = "abc.pdf";
var attach = new Buffer(fs.readFileSync("./" + fileName)).toString("base64");

var str = ["Content-Type: text/plain; charset=\"UTF-8\"\n",
    "MIME-Version: 1.0\n",
    "Content-Transfer-Encoding: 7bit\n",
    "to: ", to, "\n",
    "subject: ", subject, "\n\n",
    "Content-Type: multipart/alternate; boundary=" + boundary + nl,
    "--" + boundary,
    "Content-Type: text/plain; charset=UTF-8",
    "Content-Transfer-Encoding: 7bit" + nl,
    message + nl,
    "--" + boundary,
    "--" + boundary,
    "Content-Type: Application/pdf; name=myPdf.pdf",
    'Content-Disposition: attachment; filename=myPdf.pdf',
    "Content-Transfer-Encoding: base64" + nl,
    attach,
    "--" + boundary + "--"
].join('');

var encodedMail = new Buffer(str).toString("base64")
    .replace(/\+/g, '-')
    .replace(/\//g, '_');

resolve(encodedMail);


部分邮件如下

内容类型:多部分/替代;边界=myapp --_myapp_Content-Type:文本/纯文本; charset=UTF-8Content-Transfer-Encoding: 7bit 测试信息 --myapp--_myapp_Content-Type:应用程序/pdf; name=myPdf.pdfContent-Disposition:附件; 文件名=myPdf.pdf 内容传输编码:base64 JVBERi0xLjMgCiXi48 / TIAoxIDAgb2JqIAo8PCAKL1R5cGUgL0NhdGFsb2cgCi9QYWdlcyAyIDAgUiAKL1BhZ2VNb2RlIC9Vc2VOb25lIAovVmlld2VyUHJlZmVyZW5jZXMgPDwgCi9GaXRXaW5kb3cgdHJ1ZSAKL1BhZ2VMYXlvdXQgL1NpbmdsZVBhZ2UgCi9Ob25GdWxsU2NyZWVuUGFnZU1vZGUgL1VzZU5vbmUgCj4 +佑+ PiAKZW5kb2JqIAo1IDAgb2JqIAo8PCAKL0xlbmd0aCAyNjQzIAovRmlsdGVyIFsgL0ZsYXRlRGVjb2RlIF0gCj4 + IApzdHJlYW0KeJzdGWtT48jxu3 + FMYMkY8uep2bGkgADBrwseHntLYv3kspe9iqpbFK5fMjfT89LkuUH3H5J1UEVNZru6e7pdw94hEUXw2 + K3UpxMpLdr9872G7 / 9qtf3F92JMVdynGXYJ7xLsmY4N3f / tr5qfPPDu2 + A7Z / WhSSZRUO1YQYnIcOHilFu82 /// lq0RlhxKMLjA3yX + X + pqp91tyXZPO + wiLsU9HYJzzDFQPpAUIL6gT97tZWin + AnFKxzH199 + ssQIywTBkAIURx92EgVBEWQG4dznCc ...更多 文本...最后...==--myapp--


我认为发送带有附件的邮件的模板可能存在问题。

谁能在这里提供帮助?
谢谢

【问题讨论】:

  • 您似乎缺少一个 mimeType 属性来指定文件的类型为 application/pdf。按照 Gmail 中的Uploading Attachments 指南了解步骤。
  • @noogui 您可以在上面的代码中找到,我已将内容类型指定为 Application/pdf
  • 这些信息对您的情况有用吗? stackoverflow.com/questions/50540051/…
  • @Tanaike 感谢您的帮助。我的实际问题是我忘记放置的对齐和新行。
  • 感谢您的回复。很高兴您的问题得到了解决。

标签: javascript node.js gmail-api


【解决方案1】:

我能够使用正确的消息结构附加 PDF 文件。设置正确的 mimeType 和边界非常重要。

@Tanaike 指出的这个参考 (https://stackoverflow.com/a/50540373/13664358) 帮助很大!

这是发送带有 PDF 附件的电子邮件的完整功能:

const subject = 'My Subject';
const utf8Subject = `=?utf-8?B?${Buffer.from(subject).toString('base64')}?=`;

var fileName = "mypdf.pdf";
var attach = new Buffer.from(fs.readFileSync("./" + fileName)).toString("base64");

var emailBody = 'My Email Message';

var messageParts = [
    "MIME-Version: 1.0",
    'From: Teste <teste@teste.com>',
    'To: Teste <teste@teste.com>',
    `Subject: ${utf8Subject}`,
    "Content-Type: multipart/mixed; boundary=012boundary01",
    '',
    "--012boundary01",
    "Content-Type: multipart/alternative; boundary=012boundary02",
    '',
    "--012boundary02",
    "Content-type: text/html; charset=UTF-8", 
    "Content-Transfer-Encoding: quoted-printable",
    '',
    emailBody,
    '',
    "--012boundary02--",
    "--012boundary01",
    "Content-Type: Application/pdf; name=mypdf.pdf",
    'Content-Disposition: attachment; filename=mypdf.pdf',
    "Content-Transfer-Encoding: base64",
    '',
    attach,
    "--012boundary01--",
]

const message = messageParts.join('\n');

// The body needs to be base64url encoded.
const encodedMessage = Buffer.from(message)
  .toString('base64')
  .replace(/\+/g, '-')
  .replace(/\//g, '_')
  .replace(/=+$/, '');

const gmail = google.gmail({version: 'v1', auth});
gmail.users.messages.send({
  userId: 'me',
  requestBody: {
      raw: encodedMessage
  }
}, (err, res) => {
  if (err) return console.log('The API returned an error: ' + err);
});

注意:以上代码使用 google apis for nodejs (https://www.npmjs.com/package/googleapis)

对于多个 PDF,我们可以在 --012boundary02-- 和 --012boundary01-- 之间添加它们,如下所示:

"--012boundary02",
"Content-type: text/html; charset=UTF-8", 
"Content-Transfer-Encoding: quoted-printable",
'',
emailBody,
'',
"--012boundary02--",
"--012boundary01",
"Content-Type: Application/pdf; name=mypdf.pdf",
'Content-Disposition: attachment; filename=mypdf.pdf',
"Content-Transfer-Encoding: base64",
'',
attach,
"--012boundary01",
"Content-Type: Application/pdf; name=mypdf2.pdf",
'Content-Disposition: attachment; filename=mypdf2.pdf',
"Content-Transfer-Encoding: base64",
'',
attach2,
"--012boundary01",
"Content-Type: Application/pdf; name=mypdf3.pdf",
'Content-Disposition: attachment; filename=mypdf3.pdf',
"Content-Transfer-Encoding: base64",
'',
attach3,
"--012boundary01--",

【讨论】:

  • 如何处理多个附件?
  • @user1791914 要添加多个附件,我们可以重复 --12boundary01 部分。我已经编辑了这个问题,以考虑到多个 pdf。看看,如果您有任何问题,请告诉我 =)
猜你喜欢
  • 2016-05-29
  • 2018-08-28
  • 2016-09-22
  • 2015-10-25
  • 2017-07-24
  • 2011-02-18
  • 2015-04-16
  • 1970-01-01
  • 2016-09-28
相关资源
最近更新 更多