Django Issue: PDF Attachments Not Showing in Emails Sent via Gmail API

I’m having trouble with my Django app. It’s supposed to send emails with PDF attachments using the Gmail API. The weird thing is, the emails are going through, but the attachments are missing.

My logs show the PDF is created and attached:

[DEBUG] PDF generated: 16988 bytes
[DEBUG] PDF attached: invoice_ABC123.pdf (16988 bytes)
[INFO] Email sent. ID: 19561950e1b649a0

But when I open the email, there’s no attachment. Just the email body.

Here’s a simplified version of my code:

def send_invoice(customer_info, pdf_file):
    subject = f'Invoice - {customer_info["id"]}'
    sender = ('Auto Shop', '[email protected]')
    recipient = customer_info['email']
    email = EmailMessage(subject, 'See attached invoice', sender, [recipient])
    email.attach(f'invoice_{customer_info["id"]}.pdf', pdf_file, 'application/pdf')
    email.send()
    print(f'Sent invoice to {recipient}')

Any ideas why the attachments aren’t showing up?

hey there alexj, had similar issue once. check ur gmail api settings - sometimes attachments get blocked for security. also, try sending to diff email provider (outlook maybe?) to see if it’s gmail-specific. if that don’t work, might be worth printing the entire email object before sending to make sure attachment’s actually there. good luck!

I’ve encountered this issue before. One thing to check is the MIME type of your attachment. Make sure it’s correctly set to ‘application/pdf’. Also, verify that the PDF file is actually being read properly before attaching. You might want to add a check to ensure the file exists and isn’t empty.

Another potential cause could be file size limitations. Gmail has attachment size limits, so if your PDF is too large, it might be silently dropped. Try with a smaller PDF to rule this out.

Lastly, consider using a library like python-magic to automatically detect and set the correct MIME type. This can help ensure the attachment is properly recognized by email clients.

Hey alexj, I’ve run into this exact problem before. Here’s what fixed it for me:

Check your Gmail API scope permissions. Make sure you’ve enabled the ‘gmail.send’ scope, not just ‘gmail.readonly’. This bit me hard because the emails were sending, but attachments were getting stripped.

Also, double-check your PDF generation. Sometimes PDFs can be created with errors that email clients don’t like. Try opening the PDF manually before attaching to ensure it’s valid.

If those don’t work, you might need to Base64 encode your attachment. The Gmail API can be picky about raw binary data. Here’s a quick example:

import base64

# ... your other code ...
pdf_data = base64.b64encode(pdf_file).decode()
email.attach(f'invoice_{customer_info["id"]}.pdf', pdf_data, 'application/pdf')

Hope this helps! Let us know if you figure it out.