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
Navigate into the project directory:
cd gmail
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
π 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
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()
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
- Visit: https://myaccount.google.com/apppasswords
- Generate a password for "Mail" and "Other (Custom name)"
- 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)