I’m working on migrating our Django app from the standard email system to Mailgun API. Everything works fine for regular emails, but I’m stuck when trying to send emails with PDF attachments that are created on the fly.
The PDFs are generated dynamically by our application and aren’t saved to disk. Here’s how I currently create the PDF:
document = BytesIO()
create_report(document, parameters)
document.seek(0)
file_attachment = MIMEApplication(document.read())
file_attachment.add_header("Content-Disposition", "attachment", filename=report_name)
document.close()
Then I send it using Django’s built-in email:
from django.core.mail import EmailMultiAlternatives
email_msg = EmailMultiAlternatives(email_subject, plain_text, sender_email, recipient_list)
if html_text:
email_msg.attach_alternative(html_text, "text/html")
if file_attachment:
email_msg.attach(file_attachment)
email_msg.send()
This approach works perfectly. Now I need to do the same thing with Mailgun’s API but I can’t figure out the right way to format the attachment.
I tried this but it doesn’t work:
response = requests.post(mailgun_endpoint, auth=("api", api_key), data=email_data, files=file_attachment)
The request works fine when I remove the files parameter. The email_data dict contains all the standard fields like to, from, subject, and tags.
Can someone help me figure out the correct way to structure the PDF attachment for Mailgun’s API?