Django provides a built-in email sending functionality through the django.core.mail
module. Here's a step-by-step guide on how to use it:
Configure Email Settings in settings.py
:
First, you need to configure your email settings in the settings.py
file of your Django project. Specify the SMTP server details, such as host, port, username, password, etc. Here's an example:
python# settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'your-smtp-server.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'your-email@example.com'
EMAIL_HOST_PASSWORD = 'your-email-password'
Replace the placeholders with your actual SMTP server details.
Import the send_mail
function:
In your Django views or other parts of your code, import the send_mail
function:
pythonfrom django.core.mail import send_mail
Use send_mail
function to send an email:
Now, you can use the send_mail
function to send emails. The basic syntax is as follows:
pythonsend_mail(subject, message, from_email, recipient_list, fail_silently=False)
subject
: The subject of the email.message
: The message content of the email.from_email
: The sender's email address.recipient_list
: A list of recipient email addresses.fail_silently
: If True
, errors during sending will not raise exceptions.Example:
pythonfrom django.core.mail import send_mail
subject = 'Hello, World!'
message = 'This is a test email.'
from_email = 'your-email@example.com'
recipient_list = ['recipient1@example.com', 'recipient2@example.com']
send_mail(subject, message, from_email, recipient_list)
You can customize the message
parameter to include HTML content or use other features provided by the send_mail
function.
Advanced Usage:
Django also provides additional classes and methods for more advanced email sending, such as sending HTML emails, attaching files, etc. You can use EmailMessage
and send_mail
in combination for more control. Check the official Django documentation on sending email for more details.
That's it! You've successfully used Django's built-in email sending functionality. Make sure to test your email configuration in a development environment before deploying it to production.