python - Gmail API Not Sending Email Attachments with PDF in Django - Stack Overflow

I'm using the Gmail API to send emails with PDF attachments from my Django backend, but the attach

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:

import logging
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

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:

import logging
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
Share Improve this question edited Mar 5 at 2:26 furas 144k12 gold badges115 silver badges161 bronze badges asked Mar 4 at 14:40 Aamir QayyumAamir Qayyum 1 4
  • Where did you implement the base64 that you imported in your code? – Lime Husky Commented Mar 4 at 16:07
  • Please provide enough code so others can better understand or reproduce the problem. – Community Bot Commented Mar 4 at 22:35
  • text ``` has to be in seperate line to correctly display colored code. – furas Commented Mar 5 at 2:27
  • did you try to send it to different email? Maybe GMail removes PDF for security reason. – furas Commented Mar 5 at 2:28
Add a comment  | 

1 Answer 1

Reset to default 0

You can try encoding the PDF content in base64 before attaching it.

import base64

# Encode the PDF content in base64
pdf_content_base64 = base64.b64encode(pdf_content).decode('utf-8')

# Attach PDF
email.attach(filename, base64.b64decode(pdf_content_base64), 'application/pdf')

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745037709a4607619.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信