PDF file gets damaged when sending through Mailgun email service

I’m having trouble with PDF files getting corrupted when I send them via email using Mailgun in my Node.js application.

The original PDF file works perfectly fine on my server, but when the recipient downloads it from the email, the file appears to be damaged and won’t open properly.

Here’s the code I’m currently using to send the email with the PDF attachment:

var document = fs.readFileSync(emailData.files[0].location);
var fileAttachment = new mailgun.Attachment({
  data: document, 
  filename: emailData.files[0].title,
  contentType: 'application/pdf'
});

var emailConfig = {
  from: '[email protected]',
  to: '[email protected]',
  attachment: [fileAttachment],
  subject: 'Document attached',
  text: 'Please find the document attached'
};

mailgun.messages().send(emailConfig, function(err, result) {
  // handle response
});

I’m using the mailgun-js library and the emailData.files array contains the file path and filename information. Has anyone encountered this issue before? What could be causing the PDF corruption during the email sending process?

Check how you’re reading the file - I hit the same corruption issue with binary files and Mailgun. You might be handling the buffer data wrong. Don’t read it as raw data. Read with no encoding, then convert it properly. Also check if your server handles binary data correctly. Sometimes filesystem permissions or temp file handling mess things up. Verify file size limits too. Mailgun caps attachment sizes and big PDFs get chopped during transmission, which corrupts them. Test with a tiny PDF first to see if it’s size or encoding.

Had the exact same problem last year building an email system for documents. It’s a base64 encoding issue. When you use fs.readFileSync(), you get raw binary data, but emails need proper encoding for binary attachments. Try this - explicitly encode the PDF as base64: javascript var document = fs.readFileSync(emailData.files[0].location, 'base64'); var fileAttachment = new mailgun.Attachment({ data: Buffer.from(document, 'base64'), filename: emailData.files[0].title, contentType: 'application/pdf' }); Or just pass the file path directly to the Attachment constructor instead of reading it yourself. This fixed my corruption issues with larger PDFs and works reliably.