How can I attach a dynamically created PDF via Mailgun in Django?

Migrating our Django email system to Mailgun, in-memory PDF attachments aren’t working. For instance:

def create_document(info):
    return b'%PDF-sample%'

email_msg = build_email(subject='Test', attachment=create_document(details))
send_via_mailgun(email_msg)

In my experience, the solution was to send the attachment as a tuple containing a valid file name, the in-memory PDF content, and the correct MIME type. Instead of just passing raw bytes, I wrapped the PDF data in a BytesIO stream and then built the file tuple. This adjustment ensures Mailgun can determine the proper file name and content type. I also checked that the Mailgun API request’s attachment field was correctly formatted according to their documentation. This approach fixed my issues when migrating to dynamically generated files.

I experienced a similar challenge when dynamically generating PDFs. My breakthrough came from embedding the in-memory PDF into a well-defined file-like object that carries both a proper file name and a precise content type. Instead of merely sending raw bytes, I wrapped the data using an in-built file handling module, which ensures that the multipart form-data meets Mailgun’s API specifications. This approach not only resolved the attachment recognition problem but also provided more clarity when debugging API responses in Django.

hey, try wrapping the pdf in a BytesIO and add a proper filename, e.g. ‘document.pdf’. it fixed my mailgun attachment problems, probably because mailgun needed the mimetype and name to process it correcly.

In my experience, making Mailgun work with dynamically created PDFs in Django required a few careful adjustments. I initially had a situation where the PDF attachment was simply raw bytes, and it led to the file being misinterpreted by Mailgun. After some trial and error, I transitioned to using a file-like object via BytesIO, ensuring I assigned a proper filename as well as the correct MIME type. By formatting the attachment as a tuple that includes these details, I managed to resolve the issue. The key is to adhere strictly to Mailgun’s API expectations, which enabled successful integration with dynamically generated PDFs.