Django Email

Django provides a powerful and flexible way to send emails using its built-in email functionality. You can use this feature to send transactional emails, notifications, or other types of email communications from your application.

Configuring Email in Django

To use Django’s email functionality, you must first configure your email settings in the settings.py file. Here are the common settings:

Example:


EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'  # Default SMTP backend
EMAIL_HOST = 'smtp.gmail.com'  # Your email host, e.g., Gmail, Outlook, etc.
EMAIL_PORT = 587  # Port number for SMTP
EMAIL_USE_TLS = True  # Enable TLS for security
EMAIL_HOST_USER = 'your_email@example.com'  # Your email address
EMAIL_HOST_PASSWORD = 'your_email_password'  # Your email password or app password

Sending Email

Django provides the send_mail() function to send simple emails. Here’s an example:

Example


from django.core.mail import send_mail

def send_simple_email():
    send_mail(
        'Subject of the Email',  # Email subject
        'This is the message body.',  # Email message
        'from@example.com',  # Sender email
        ['to@example.com'],  # Recipient email(s)
        fail_silently=False,  # Raise an exception if sending fails
    )

Sending Emails with Attachments

For more advanced email functionality, use EmailMessage:

Example


from django.core.mail import EmailMessage

def send_email_with_attachment():
    email = EmailMessage(
        'Subject of the Email',
        'This is the message body.',
        'from@example.com',
        ['to@example.com'],
    )
    email.attach_file('/path/to/attachment.pdf')
    email.send()

Use HTML Emails

Django also supports sending HTML emails.

Example:


from django.core.mail import EmailMultiAlternatives

def send_html_email():
    subject, from_email, to = 'Subject', 'from@example.com', 'to@example.com'
    text_content = 'This is the plain text message.'
    html_content = '<p>This is the <strong>HTML</strong> message.</p>'
    msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
    msg.attach_alternative(html_content, "text/html")
    msg.send()