Attach pdf file to django send_mail

To attach a PDF file to a Django send_mail message, you can use the attachments parameter in the send_mail function. Here's an example:

from django.core.mail import send_mail
from django.core.files.uploadedfile import SimpleUploadedFile

# Create a PDF file
pdf_file = open('path/to/your/pdf/file.pdf', 'rb')
pdf_data = pdf_file.read()
pdf_file.close()

# Create a SimpleUploadedFile object
pdf_file_obj = SimpleUploadedFile('pdf_file.pdf', pdf_data, content_type='application/pdf')

# Send the email with the attached PDF file
send_mail(
    'Subject',
    'Body',
    '[email protected]',
    ['[email protected]'],
    attachments=[pdf_file_obj],
    fail_silently=False,
)

In this example, we first open the PDF file and read its contents into a byte string. We then create a SimpleUploadedFile object, passing the file name, file data, and content type to the constructor. Finally, we pass the SimpleUploadedFile object to the attachments parameter of the send_mail function.

Note that the SimpleUploadedFile object is a special type of file object that can be used with Django's send_mail function. It's not the same as a regular file object, so make sure to use the correct type when creating the file object.

Also, make sure to set the content_type parameter to the correct MIME type for the PDF file, which is application/pdf in this case.

If you're using Django 3.1 or later, you can also use the EmailMessage class to attach files to an email message. Here's an example:

from django.core.mail import EmailMessage

# Create a PDF file
pdf_file = open('path/to/your/pdf/file.pdf', 'rb')
pdf_data = pdf_file.read()
pdf_file.close()

# Create an EmailMessage object
email = EmailMessage(
    'Subject',
    'Body',
    '[email protected]',
    ['[email protected]'],
)

# Attach the PDF file to the email message
email.attach('pdf_file.pdf', pdf_data, 'application/pdf')

# Send the email
email.send()

In this example, we create an EmailMessage object and attach the PDF file to it using the attach method. We then send the email using the send method.