DEV Community

Sospeter Mong'are
Sospeter Mong'are

Posted on

Testing and Sending Emails in Django Using Gmail SMTP

Django provides a simple yet powerful framework for handling emails in your applications. In this article, we’ll walk you through the steps to send emails using Gmail's SMTP server in a Django project.


βœ… Step-by-Step Guide

1. πŸ“ Create a Django Project

Start by creating a new Django project named gmail:

django-admin.py startproject gmail
Enter fullscreen mode Exit fullscreen mode

Navigate into the project directory:

cd gmail
Enter fullscreen mode Exit fullscreen mode

2. βš™οΈ Configure Email Settings in settings.py

Open your settings.py file and add the following configuration to enable Gmail as your email backend:

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = '[email protected]'           # Replace with your Gmail address
EMAIL_HOST_PASSWORD = 'your_email_password'       # Use an App Password if 2FA is enabled
EMAIL_PORT = 587
Enter fullscreen mode Exit fullscreen mode

πŸ” Security Tip: Never commit your email credentials to version control. Use environment variables or Django’s decouple package to manage sensitive settings securely.


3. πŸ’» Start the Django Shell

Launch the interactive Django shell to test email sending:

python manage.py shell
Enter fullscreen mode Exit fullscreen mode

4. πŸ“€ Send an Email

In the shell, import the EmailMessage class and send your email:

from django.core.mail import EmailMessage

email = EmailMessage(
    subject='Subject',
    body='This is the body of the email.',
    to=['[email protected]']  # Replace with the recipient's email
)

email.send()
Enter fullscreen mode Exit fullscreen mode

You should see 1 returned in the shell, indicating the email was successfully sent.


πŸ›  Common Issues & Fixes

πŸ” Enabling Access for Gmail

If you see an authentication error, make sure to:

  • Enable "Less secure app access" (not recommended for production)
  • OR use an App Password if your Gmail account has 2-Step Verification enabled.

πŸ’‘ Using App Passwords

  1. Visit: https://myaccount.google.com/apppasswords
  2. Generate a password for "Mail" and "Other (Custom name)"
  3. Use the generated password in your EMAIL_HOST_PASSWORD field

βœ… Conclusion

Using Gmail’s SMTP server with Django is straightforward and effective for sending development or transactional emails. For production environments, consider using dedicated email services like SendGrid, Mailgun, or Amazon SES for better scalability and reliability.


Next Steps:

  • Wrap email sending in views or background tasks (e.g., with Celery)
  • Add templates for rich HTML emails
  • Use environment variables to manage sensitive configurations

Top comments (0)