Django send email

Prerequisites

Importance of sending emails

  • Emails play a critical role in web applications.
  • From user authentication, password resets, to marketing campaigns, emails provide a direct line of communication with users.
  • Sending emials allows us to the following things

    1. Notify users about updates or activities.
    2. Send account activation or password reset links.
    3. Handle customer support queries or feedback.

Setting Up Email in Django

  • The first step to sending emails in Django is configuring the email backend.
  • Django supports multiple email backends such as SMTP, console, and file-based backends.
  • For production purposes, we typically use an SMTP server.
  • open the my_project/settings.py file and configure the SMTP backend

my_project/settings.py

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'your-email-password'
DEFAULT_FROM_EMAIL = '[email protected]'

Django code to send email

  • Look at the code below to learn how to send the email in django.
from django.core.mail import send_mail

def send_email():
    subject = "Django test email"
    body = "Hey, I'm testing the django email functionality"
    from_email = "[email protected]"
    to = ['[email protected]']
    send_mail(subject, body, from_email, to, fail_silently=False)

Types of emails in django

Simple Email

  • Uses the send_mail() function to send a plain text email.
from django.core.mail import send_mail
send_mail(
    'Subject',
    'Message body',
    '[email protected]',
    ['[email protected]'],
    fail_silently=False,
)

HTML Email

  • Sends an email with HTML content.
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string

def send_html_email():
    subject = 'Subject'
    from_email = '[email protected]'
    to = '[email protected]'
    text_content = 'This is a plain text version of the email.'
    html_content = render_to_string('email_template.html', {'context_var': 'value'})

    msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
    msg.attach_alternative(html_content, "text/html")
    msg.attach_file('/path/to/file.pdf')
    msg.send()

Email with Attachments

  • Sends an email with file attachments.
from django.core.mail import EmailMessage

def send_email_with_attachment():
    email = EmailMessage(
        'Subject',
        'Message body',
        '[email protected]',
        ['[email protected]'],
    )
    email.attach_file('/path/to/file.pdf')  # Attach a file
    email.send()

Mass Email (Bulk Email)

  • Sends multiple emails to different recipients efficiently.
from django.core.mail import send_mass_mail

message1 = ('Subject1', 'Message body 1', '[email protected]', ['[email protected]'])
message2 = ('Subject2', 'Message body 2', '[email protected]', ['[email protected]'])

send_mass_mail((message1, message2), fail_silently=False)

Conclusion

  • Django provides flexible tools for sending a variety of emails, whether they are plain-text, HTML-based, or include attachments.
  • By configuring the email backend and utilizing the correct email functions, you can seamlessly integrate email communication into your Django applications.
  • For production environments, make sure to select an appropriate email service provider to ensure high deliverability and reliability.