Gmail API Not Sending Email Attachments with PDF in Django
I'm using the Gmail API to send emails with PDF attachments from my Django backend, but the attachment is not appearing in the email — only the email body is received.
Here are the logs showing the PDF is generated and attached correctly: [DEBUG] Generated PDF size: 16988 bytes[DEBUG] Attaching PDF: invoice_EJ70FEX.pdf (size: 16988 bytes) [INFO] Email sent successfully. Message ID: 19561950e1b649a0
However, when I receive the email, no attachment is visible.
Here's the email-sending code I'm using:
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from django.conf import settings
from email.utils import formataddr
import base64
logger = logging.getLogger(__name__)
def send_damage_invoice(driver_data, pdf_content):
"""Send damage invoice email with PDF attachment."""
try:
logger.debug("Preparing damage invoice email for %s (%s)",
driver_data['name'], driver_data['vrm'])
subject = f'Damage Charges Invoice - {driver_data["vrm"]}'
from_email = formataddr(('H&S Autocare', settings.DEFAULT_FROM_EMAIL))
to_email = driver_data['email']
# Create context for email template
context = {
'driver_name': driver_data['name'],
'vrm': driver_data['vrm']
}
# Render email content
html_content = render_to_string('emails/damage_invoice.html', context)
text_content = strip_tags(html_content)
# Create email message
email = EmailMultiAlternatives(
subject=subject,
body=text_content,
from_email=from_email,
to=[to_email]
)
email.attach_alternative(html_content, "text/html")
# Attach PDF
filename = f'invoice_{driver_data["vrm"]}.pdf'
logger.debug("Attaching PDF: %s (size: %d bytes)", filename, len(pdf_content))
email.attach(filename, pdf_content, 'application/pdf')
email.send(fail_silently=False)
logger.info("Email sent successfully to %s", to_email)
return True
except Exception as e:
logger.error("Failed to send damage invoice email: %s", str(e))
raise