Kerhael
Kerhael

Reputation: 519

Stripe: attach invoice pdf to email

I'm currently trying to send emails with attached pdf invoices to customers with nodejs but I can't figure out how to get pdf file from invoice_pdf field.

I tried fs, got and request but I am not able to get the file content ever.

for example I tried:

let file = await got(invoice.invoice_pdf)
let fileContent = Buffer.from(file['body'])
...
// mail conf
attachments: [{
    'type': 'application/pdf',
    'name': invoice.number + '.pdf',
    'content': fileContent.toString('base64'),
}],

There is a pdf attached to the received email but it is a blank page with no content.

Any help?
Thanks a lot

EDIT: doc of Mandrill's attachments enter image description here

Upvotes: 0

Views: 1689

Answers (2)

Kerhael
Kerhael

Reputation: 519

We figured it out, using streams:

async function readFile(url: string): Promise<Buffer> {
    return new Promise(function(resolve,reject){
        const bufs = []
        let finalBuf = Buffer.from('')
        got.stream(url)
        .on('data', d => bufs.push(d))
        .on('end', async function () {
            finalBuf = Buffer.concat(bufs)
            resolve(finalBuf)
        })
        .on('error', reject)
    })
}

export async function sendInvoiceEmail(invoice: Stripe.Invoice) {
    try {
            ...
            const finalBuf = await readFile(invoice.invoice_pdf)

            const options = {
                ...
                attachments: [
                    {
                        'type': 'application/pdf',
                        'name': 'invoice.pdf',
                        'content': finalBuf.toString('base64'),
                    }
                ],
            }

            await MailerClient.send(options)
    } catch (err) {
        logger.error(err, 'Error while trying to send mail')
        throw err
    }
}

Thanks to those who tried to help :)

Upvotes: 2

Vinay Kashyap
Vinay Kashyap

Reputation: 101

Did you try using the NPM Package pdfreader or pdf2json these packages will help you read the content firstly then you can store the data into a variable then pass it into the attachments.

Upvotes: 0

Related Questions