1

I saw this question but my code seems to be slightly different and not working. Sending a PDF created dynamically as an attachment using PDFKit in a nodejs application

the main difference is that i am sending this email from the backend not the browser.

Also to note that the file generated is genreated fine so it's probably an issue with passing it on to the email.

const Email = require('email-templates');
const PdfKit = require('pdfkit');
const SVGToPDF = require('svg-to-pdfkit');
const fs = require('fs');

const service =  new Email({
  message: {
    from: 'aaron.test@gmail.com'
  },
  send: true
  transport: require('../config/smtp.json') // my smtp config. Works without attachment
});

function generatePdfAndSend() {
 var doc = new PdfKit();

    const stream = doc.pipe(fs.createWriteStream("output.pdf"));

    doc.font('backend/fonts/MADE Canvas Regular PERSONAL USE.otf')
      .fontSize(25)
      .text('sample text', 100, 100);

    fs.readFile('backend/images/Happy Easter 5.svg', 'utf8', (err, contents) => {
      SVGToPDF(doc, contents, 100, 200, {});
      doc.end();
stream.on('finish', function() {
          sendEmail("templateName", "myEmail", doc);
        });

    });
}


function sendEmail(template, to, attachment) {
    service.send({
    template: template,
    message: {
      to: to,
      attachments: [
        {
          filename: 'text1.pdf',
          content: attachment,
          contentType: 'application/pdf'
        }
      ]
    },
    locals: vars

  })
    .then(console.log).catch(console.error);
}
mangusbrother
  • 3,988
  • 11
  • 51
  • 103

2 Answers2

0

I cannot see anything in the documentation that allows an object to be passed as an attachment.

Instead of passing the PdfKit object to your sendEmail function. Pass the location on disk where you output the file.

https://community.nodemailer.com/using-attachments/

Classified
  • 232
  • 1
  • 6
  • do you know if its possible to not even save it to file? just pass the stream to the email function? – mangusbrother Jan 09 '19 at 07:23
  • 1
    Yeah looks like it can be done. Check here https://stackoverflow.com/questions/40275397/sending-a-pdf-created-dynamically-as-an-attachment-using-pdfkit-in-a-nodejs-appl – Classified Jan 09 '19 at 08:39
0

i use following ,note path is path of saved pdf and attachments is array of attachment object,and it works like a charm

 attachments:[{
            filename:'reports.pdf',
            path: __dirname+'/files/output.pdf'//,
            //contentType: 'application/pdf'
        }]
Ghazaleh Javaheri
  • 1,829
  • 19
  • 25