Sending emails with attachments is a common requirement in many web applications. In Django, the built-in send_mail
function allows you to send simple text-based emails. However, to send emails with attachments, we need to use the EmailMessage
class. In this blog, we will explore how to send email with attachments in Django.
Note: For this tutorial, we are using our previous blog on How to send email in Django and DRF.
Step 1: Install Required Packages
First, make sure you have Django installed. Additionally, if you want to use file attachments, install python-magic
library to detect file types:
pip install Django python-magic
python-magic
is necessary for automatically detecting the MIME type of file attachments when sending emails, ensuring compatibility with different email clients.
Step 1: Configure Django Email Settings
Ensure that you have configured your email settings properly in your project’s settings.py
file. For example:
# settings.py
# ... other settings ...
# Email Configuration
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'your_email@example.com' # Replace with your email address
EMAIL_HOST_PASSWORD = 'your_email_password' # Replace with your email password
Replace ‘your_smtp_host’, ‘your_email@example.com’, and ‘your_email_password’ with your actual SMTP server details and email credentials.
Please watch bellow video, to send email using Gmail.
Step 3: Create the Email Utility Function
In your Django app, create a new file named email_utils.py
. This file will contain the email utility function for sending emails with attachments:
# email_utils.py
import magic
import os
from django.core.mail import EmailMessage
def send_email_with_attachment(subject, message, from_email, recipient_list, attachment_path):
with open(attachment_path, 'rb') as file:
file_content = file.read()
mime_type = magic.from_buffer(file_content, mime=True)
# Extract the filename from the attachment_path
file_name = os.path.basename(attachment_path)
email = EmailMessage(subject, message, from_email, recipient_list)
email.attach(file_name, file_content, mime_type)
# Send the email
email.send()
Step 4: Create the View Function
In your views.py
file, update the view function to import and use the email utility function:
# views.py
from django.shortcuts import render
from django.conf import settings
from .email_utils import send_email_with_attachment
def my_email_with_attachment_view(request):
# ... Your view logic ...
subject = 'Email with Attachment'
message = 'Please find the attached file.'
from_email = 'your_email@example.com' # Replace with your email address
recipient_list = ['recipient@example.com'] # Replace with the recipient's email address
# Attach the file
# Attach the file from the sibling folder "documents" of the templates folder
attachment_path = 'documents/sample.pdf' # Replace with the relative path to the file from the root directory
file_path = settings.BASE_DIR / attachment_path
send_email_with_attachment(subject, message, from_email, recipient_list, attachment_path)
# ... Rest of your view logic ...
return HttpResponse("Email with Attachment Sent Successfully!")
Replace file path according to your requirements, you can attach pdfs, images, videos, etcs.
Step 5: Define the URL Pattern
In your app’s urls.py
file, update the URL pattern to access the view:
# urls.py
from django.urls import path
from . import views
urlpatterns = [
# Other URL patterns in your app
path('email-attachment/', views.my_email_with_attachment_view, name='email-template'),
]
Step 6: Test the Email Attachment Functionality
Run your Django development server and navigate to the URL /email-attachment/
. This will trigger the send_email_with_attachment_view
view, and the email with the attachment will be sent.
Conclusion
By separating the email utility function from the view, we have organized our code better and made it more modular. The email utility function can be easily reused in other parts of the application. Sending emails with attachments in Django is now simple and efficient. Happy coding!
Find this tutorial on Github.