How to Send Email with Attachment in Python Django?

Published On: 08/07/2022 | Category: Django Python

If you need to see example of how to send email with attachment in python django. you can see send email with attachment in python django example. This tutorial will give you simple example of how to django send email with attachment. I explained simply about sending emails with attachment in django.

Let's see bellow example I explained simply about sending emails with attachment in django.

Step 1 : Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject exampleapp
Step 2 : Create a App
python3 manage.py startapp sendmail

Next, you need to add it in the settings.py file as follows:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'sendmail',
]
Step 3 : Setup Email Configuration

Next step, we will modify the settings.py file and update the smtp email backends settings to configure:

settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = 'bhaveshs.aa*******@gmail.com'
EMAIL_HOST_PASSWORD = 'YOUR_APP_PASSWORD'  
Step 4 : Create a FormClass

First of all in this step we will create a new file called forms.py and create a Django form you need to use Django Form Class

sendmail/forms.py
from django import forms

# creating a form
class EmailForm(forms.Form):
    email = forms.EmailField()
    subject = forms.CharField(max_length=100)
    attach = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
    message = forms.CharField(widget=forms.Textarea(attrs={'rows': 4}))
Step 5 : Creating the Views

In this step, we need to create the views for performing fetch record to the database.Open the sendmail/views.py file and add:

sendmail/views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.views import View
from django.core.mail import EmailMessage
from django.conf import settings
from .forms import EmailForm

class EmailAttachementView(View):
    form_class = EmailForm
    template_name = 'index.html'

    def get(self, request, *args, **kwargs):
        form = self.form_class()
        return render(request, self.template_name, {'email_form': form})

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST, request.FILES)

        if form.is_valid():
            
            subject = form.cleaned_data['subject']
            message = form.cleaned_data['message']
            email = form.cleaned_data['email']
            attach = request.FILES['attach']

            try:
                mail = EmailMessage(subject, message, settings.EMAIL_HOST_USER, [email])
                mail.attach(attach.name, attach.read(), attach.content_type)
                mail.send()
                return render(request, self.template_name, {'email_form': form, 'error_message': 'Sent email to %s'%email})
            except:
                return render(request, self.template_name, {'email_form': form, 'error_message': 'Either the attachment is too big or corrupt'})

            return render(request, self.template_name, {'email_form': form, 'error_message': 'Unable to send email. Please try again later'})
Step 6 : Creating the Templates

Next, open the sendmail/templates/index.html file and the add:

{% load crispy_forms_tags %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Profile Image</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h4>How to Send Email with Attachment in Python Django?</h4>
                    </div>
                    <div class="card-body">
                        {% if error_message %}
                            <div class="alert alert-success" role="alert">
                                {{error_message}}
                            </div>
                        {% endif %}
                        {% if email_form %}
                            <form method="POST" action ="" enctype="multipart/form-data">
                                {% csrf_token %}
                                {{email_form|crispy}}
                                <button type="submit" class="btn btn-success">Send Email</button>
                            </form>
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
Step 7 : Creating Urls

In this section, we’ll create the urls to access our views.Go to the urls.py sendmail/urls.py file and update it as follows:

sendmail/urls.py
from django.urls import path
from sendmail.views import EmailAttachementView

urlpatterns = [
    path('send-email', EmailAttachementView.as_view(), name='emailattachment')
]

Next, we will require the modify the urls.py your root preoject folder lets update the file.

exampleapp/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('sendmail.urls')),
]
Step 8 : Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python manage.py runserver

Next, go to the url address bar with a web browser.

http://localhost:8000/send-email
Output

I Hope It will help you....