Django send_mail
In Django, you can send emails using the send_mail
function from the django.core.mail
module. Here's a basic example:
from django.core.mail import send_mail
subject = 'Hello from Django'
message = 'This is a test email sent from Django'
from_email = '[email protected]'
recipient_list = ['[email protected]']
send_mail(subject, message, from_email, recipient_list)
In this example, send_mail
takes five arguments:
subject
: The subject of the email.message
: The body of the email.from_email
: The email address that the email is sent from.recipient_list
: A list of email addresses that the email is sent to.fail_silently
: A boolean that determines whether to raise an exception if the email cannot be sent (default isFalse
).
You can also specify additional arguments, such as:
auth_user
: The username to use for authentication (default isNone
).auth_password
: The password to use for authentication (default isNone
).connection
: The connection to use for sending the email (default isNone
).
Here's an example with additional arguments:
from django.core.mail import send_mail
subject = 'Hello from Django'
message = 'This is a test email sent from Django'
from_email = '[email protected]'
recipient_list = ['[email protected]']
auth_user = 'your_username'
auth_password = 'your_password'
send_mail(subject, message, from_email, recipient_list, auth_user=auth_user, auth_password=auth_password)
You can also use the EmailMessage
class from the django.core.mail
module to create a more complex email message:
from django.core.mail import EmailMessage
subject = 'Hello from Django'
message = 'This is a test email sent from Django'
from_email = '[email protected]'
recipient_list = ['[email protected]']
email = EmailMessage(subject, message, from_email, recipient_list)
email.send()
In this example, you can add additional headers, attachments, and other features to the email message.
It's also worth noting that you can use a custom email backend by setting the EMAIL_BACKEND
setting in your settings.py
file. For example:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
This will allow you to use a custom SMTP server to send emails.