通过SendGrid发送受密码保护的附件

时间:2019-09-27 21:21:13

标签: pdf sendgrid email-attachments password-protection qpdf

我想使用SendGrid for nodejs将受密码保护的pdf发送为电子邮件附件。

我尝试使用qpdf来密码保护pdf。这将输出一个新的pdf文件,该文件在本地受密码保护。然后,我尝试从该文件中读取数据,并按照SendGrid的文档将其作为附件的内容发送。

const fs = require('fs');
const qpdf = require('node-qpdf');

const options = {
  keyLength: 128,
  password: 'FAKE_PASSWORD',
  outputFile: filename
}
const attachments = []

await new Promise(res => {
  const writeStream = fs.createWriteStream('/tmp/temp.pdf');
  writeStream.write(buffer, 'base64');
  writeStream.on('finish', () => {
      writeStream.end()
  });
  res();
})
await qpdf.encrypt('/tmp/temp.pdf', options);
const encryptedData = await new Promise(res => {
  const buffers = []
  const readStream = fs.createReadStream('/tmp/temp.pdf');
  readStream.on('data', (data) => buffers.push(data))
  readStream.on('end', async () => {
    const buffer = Buffer.concat(buffers)
    const encryptedBuffer = buffer.toString('base64')
    res(encryptedBuffer)
  })
})
attachments.push({
  filename,
  content: encryptedData,
  type: 'application/pdf',
  disposition: 'attachment'
})

我收到了带有pdf附件的电子邮件,但没有密码保护。这两个库可能吗?

1 个答案:

答案 0 :(得分:1)

您似乎正在发送未加密的文件。也许行得通吗?

const fs = require('fs');
const qpdf = require('node-qpdf');

const options = {
  keyLength: 128,
  password: 'FAKE_PASSWORD'
}
const attachments = []

await new Promise(res => {
  const writeStream = fs.createWriteStream('/tmp/temp.pdf');
  writeStream.write(buffer, 'base64');
  writeStream.on('finish', () => {
      writeStream.end()
      res(); // CHANGED
  });
})
await qpdf.encrypt('/tmp/temp.pdf', options, filename); // CHANGED
const encryptedData = await new Promise(res => {
  const buffers = []
  const readStream = fs.createReadStream(filename); // CHANGED
  readStream.on('data', (data) => buffers.push(data))
  readStream.on('end', async () => {
    const buffer = Buffer.concat(buffers)
    const encryptedBuffer = buffer.toString('base64')
    res(encryptedBuffer)
  })
})
attachments.push({
  filename,
  content: encryptedData,
  type: 'application/pdf',
  disposition: 'attachment'
})