首页 > 解决方案 > 使用 Mailgun 从 Base64 字符串发送 pdf 附件

问题描述

我有一个由另一个函数生成的 pdf,它返回一个 Base64 字符串。然后我想将它作为附件附加到 Mailgun 电子邮件中,该附件内置于 MeteorMailgun中。我看到有很多从文件系统附加文件的示例,但我没有看到任何使用 Base64 的内容。

我有一种方法可以生成 Base64 字符串并使用前缀连接以将 Base64 转换为 PDF

//returns base64 string: looks like "YW55IGNhcm5hbCBwbGVhc3VyZQ=="
const base64AttachmentString = 'data:application/pdf;base64,' + generatePdfBase64();

import { Email } from "meteor/email";

Email.send({
  to: "email@example.com",
  from: "John Smith <johnsmith@example.com>",
  subject: "Sending Base64 as PDF",
  html: generatedHTMLTemplate,
  attachment: base64AttachmentString
});

有没有办法发送 Base64 附件,Mailgun 会将其识别为 PDF?我知道这对于其他邮件程序是可能的,例如NodemailerSendGrid

标签: javascriptmeteorbase64email-attachmentsmailgun

解决方案


似乎流星的电子邮件要求您添加attachments密钥,这应该是一个附件数组。

至于附件的选项 -有多个

    {   // utf-8 string as an attachment
        filename: 'text1.txt',
        content: 'hello world!'
    },
    {   // binary buffer as an attachment
        filename: 'text2.txt',
        content: new Buffer('hello world!','utf-8')
    },
    {   // file on disk as an attachment
        filename: 'text3.txt',
        path: '/path/to/file.txt' // stream this file
    },
    {   // filename and content type is derived from path
        path: '/path/to/file.txt'
    },
    {   // stream as an attachment
        filename: 'text4.txt',
        content: fs.createReadStream('file.txt')
    },
    {   // define custom content type for the attachment
        filename: 'text.bin',
        content: 'hello world!',
        contentType: 'text/plain'
    },
    {   // use URL as an attachment
        filename: 'license.txt',
        path: 'https://raw.github.com/andris9/Nodemailer/master/LICENSE'
    },
    {   // encoded string as an attachment
        filename: 'text1.txt',
        content: 'aGVsbG8gd29ybGQh',
        encoding: 'base64'
    },
    {   // data uri as an attachment
        path: 'data:text/plain;base64,aGVsbG8gd29ybGQ='
    }

特别是在您的示例中,您可以使用:

const base64AttachmentString = 'data:application/pdf;base64,' + generatePdfBase64();

import { Email } from "meteor/email";

Email.send({
  to: "email@example.com",
  from: "John Smith <johnsmith@example.com>",
  subject: "Sending Base64 as PDF",
  html: generatedHTMLTemplate,
  attachments: [
    {
      path: base64AttachmentString
    }
  ]
});

推荐阅读