How to Send Emails with Django: A Step-by-Step Guide
Tags: webdev, beginners, programming, tutorial
Published: 2023-08-02 17:24:34

Django, a powerful web framework for Python, makes it easy to build web applications, including ones that involve sending emails. Sending emails is a common requirement in many web applications, whether it's for user registration, password reset, notifications, or any other communication with users. In this step-by-step guide, we will walk you through the process of setting up and **sending emails using Django**.

## Step 1: Set up Django Project

Assuming you have Python installed on your system, start by creating a new Django project if you haven't already:

```
django-admin startproject projectname
cd projectname
```

## Step 2: Create Django App

Next, create a new Django app within your project:

```
python manage.py startapp appname

```
## Step 3: Configure Email Settings

In your Django project's settings.py file, configure the email settings. Open the settings.py file and find the `EMAIL_BACKEND` and `EMAIL_HOST` settings. You can use Django's built-in SMTP backend for development and testing purposes, but for production, you'll need to use a proper email service provider.

For production, you should use a proper email service provider like Gmail, Mailgun, SendGrid, etc.:

```
# settings.py

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'your_email_host'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'your_email_username'
EMAIL_HOST_PASSWORD = 'your_email_password'

```


Remember to replace 'your_email_host', 'your_email_username', and 'your_email_password' with your actual email service provider details.

## Step 4: Create Email Template (Optional)

You can create an HTML email template to make your emails look more professional and engaging. Create a folder named templates within your app directory and then create a sub-folder named emails. Inside this folder, create an HTML file for your email content. For example, registration_email.html:

```
<!-- registration_email.html -->

<!DOCTYPE html>
<html>
<head>
    <title>Welcome to our website!</title>
</head>
<body>
    <h2>Hello {{ username }},</h2>
    <p>Thank you for registering on our website. We're excited to have you onboard!</p>
    <p>Best regards,</p>
    <p>The Website Team</p>
</body>
</html>

```

## Step 5: Sending Emails from Django Views

Now that your email settings are configured, and the email template (if you have one) is ready, it's time to send emails from your Django views. Open your app's views.py file and import the necessary modules:

```
# views.py

from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils.html import strip_tags

```
Next, define a function to send the email:

```
# views.py

def send_registration_email(request):
    # Get the user's email and username
    email = 'user@example.com'  # Replace with the user's email address
    username = 'John Doe'       # Replace with the user's username

    # Prepare the email content
    subject = 'Welcome to Our Website!'
    html_message = render_to_string('emails/registration_email.html', {'username': username})
    plain_message = strip_tags(html_message)

    # Send the email
    send_mail(subject, plain_message, 'your_email_sender@example.com', [email], html_message=html_message)

    return HttpResponse('Email sent successfully!')

```

In this example, we're sending a welcome email to a user who has just registered on our website. The send_mail() function is used to send the email, and it takes the subject, plain text message, sender email address, recipient list, and the HTML message as parameters.

## Step 6: Configure URL and Test

Finally, you need to configure a URL in your app's urls.py file to trigger the email sending process. Add a URL pattern that maps to the view function you created earlier:

```
# urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('send_email/', views.send_registration_email, name='send_email'),
]
```


Now, you can run your Django development server and visit the URL http://127.0.0.1:8000/send_email/. This will trigger the send_registration_email view, and the welcome email will be sent to the specified email address.

## Conclusion

**Congratulations!** You have successfully set up and sent emails using Django. You can extend this functionality to other parts of your web application, such as sending password reset emails, notifications, and more.

Keep in mind that when deploying your application to production, you should use a proper email service provider for reliability and security. Always handle sensitive information like email passwords securely and follow best practices for email communication in your web application.