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

Sending password protected attachments via SendGrid

我想使用 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 附件的电子邮件,但它没有密码保护。这可能与这两个库有关吗?

您似乎发送了未加密的文件。也许这会奏效?

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'
})