Django send mail
Django provides a built-in way to send emails using the django.core.mail
module. Here's a step-by-step guide on how to send emails in Django:
Step 1: Install required packages
You need to install the django.core.mail
module and a mail backend (e.g., django.core.mail.backends.smtp.EmailBackend
) to send emails. You can install them using pip:
pip install django
pip install django-core-mail
Step 2: Configure email settings
In your Django project's settings.py
file, add the following settings:
EMAIL_HOST = 'your_email_host' # e.g., 'smtp.gmail.com'
EMAIL_PORT = 587 # or 25, depending on your email provider
EMAIL_USE_TLS = True # or False, depending on your email provider
EMAIL_HOST_USER = 'your_email_username' # e.g., '[email protected]'
EMAIL_HOST_PASSWORD = 'your_email_password'
Replace the placeholders with your actual email settings.
Step 3: Send an email
To send an email, you can use the send_mail()
function from django.core.mail
:
from django.core.mail import send_mail
subject = 'Hello from Django!'
message = 'This is a test email sent from Django.'
from_email = 'your_email_username' # e.g., '[email protected]'
to_email = '[email protected]'
send_mail(subject, message, from_email, [to_email])
This will send an email to the recipient with the specified subject, message, and from email.
Step 4: Use a mail backend
To use a mail backend, you need to specify it in your settings.py
file:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
This will use the SMTP mail backend to send emails.
Step 5: Test your email settings
To test your email settings, you can use the send_mail()
function with a test email:
from django.core.mail import send_mail
subject = 'Test email'
message = 'This is a test email.'
from_email = 'your_email_username' # e.g., '[email protected]'
to_email = 'your_email_username' # e.g., '[email protected]'
send_mail(subject, message, from_email, [to_email])
If everything is set up correctly, you should receive a test email in your inbox.
Additional tips
- Make sure to replace the placeholders with your actual email settings.
- You can customize the email settings by using environment variables or a separate configuration file.
- You can also use a third-party library like
django-email
to send emails. - If you're using Gmail, you may need to allow less secure apps to access your account.