Sending Email’s In Django -Free Django Tutorials

Django is one of the framework that comes with a ready and easy-to-use light engine for sending and receiving email’s.Although in python,to send or receive email you just need to import smtplib ,in django for email functionality user just have to import django.core.mail.

Quick Example:

from django.core.mail import send_mail

send_mail(
    'Subject here',
    'Here is the message.',
    'from@example.com',
    ['to@example.com'],
    fail_silently=False,
)

In django mail is sent using SMTP, where the host and port are specified in the EMAIL_HOST and EMAIL_PORT settings.If user set the EMAIL_HOST_USER and EMAIL_HOST_PASSWORD settings,then they are used to authenticate to the SMTP server,also EMAIL_USE_TLS and EMAIL_USE_SSL settings were used to control whether a secure connection is used or not.

send_mail()

Syntax:

send_mail(subject, message, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None, html_message=None)

Required Parameters

  • subject: A string(the subject of the email)
  • message: A string(a message which you want to send via email)
  • from_email: A string(sender’s email address)
  • recipient_list:  A list of strings,each string contain an email address.

Optional Parameters

  • fail_silently: A boolean value.If it is set to False, then send_mail will raise an smtplib.SMTPException.
  • auth_user: This is the optional username which will be used by django to authenticate to the SMTP server.If this is not provided by user while declaring send_mail then django will use the value of EMAIL_HOST_USER  from the settings.py file.
  • auth_password: This is the  optional password which will be used to use to authenticate to the SMTP server.If this isn’t provided by user then django will use the value of EMAIL_HOST_PASSWORD  from the settings.py file.
  • connection: This is the optional email backend which will be used to send the mail.

The return value of the send_mail will be the number of successfully delivered messages (which can be 0 or 1 since it can only send one message).

Examples

This following example will sends a single email to 2 users,with them both appearing in the “To:”:

send_mail(
    'Subject',
    'Message.',
    'from@example.com',
    ['rana32@example.com', 'hardik1670@example.com'],
)

This following example will sends a message to 2 users,with them both receiving a separate email:

datatuple = (
    ('Subject', 'Message.', 'from@example.com', ['john@example.com']),
    ('Subject', 'Message.', 'from@example.com', ['jane@example.com']),
)
send_mass_mail(datatuple)
Here is an example view function that takes a subject, message and from_email as a input from the request’s POST data.
from django.core.mail import BadHeaderError, send_mail
from django.http import HttpResponse, HttpResponseRedirect

def send_email(request):
    subject = request.POST.get('subject', '')
    message = request.POST.get('message', '')
    from_email = request.POST.get('from_email', '')
    if subject and message and from_email:
        try:
            send_mail(subject, message, from_email, ['rana32@example.com'])
        except BadHeaderError:
            return HttpResponse('Invalid header found.')
        return HttpResponseRedirect('/thanks/welcome/')
    else:
        # In reality we'd use a form class
        # to get proper validation errors.
        return HttpResponse('Enter correct values')

Sending multiple emails

from django.core import mail
connection = mail.get_connection()

# Manually open the connection
connection.open()

# Construct an email message that uses the connection
email1 = mail.EmailMessage(
    'Hello',
    'Body goes here',
    'from@example.com',
    ['to1@example.com'],
    connection=connection,
)
email1.send() # Send the email

# Construct two more messages
email2 = mail.EmailMessage(
    'Hello',
    'Body goes here',
    'from@example.com',
    ['to2@example.com'],
)
email3 = mail.EmailMessage(
    'Hello',
    'Body goes here',
    'from@example.com',
    ['to3@example.com'],
)

# Send the two emails in a single call -
connection.send_messages([email2, email3])
# closing the connection
connection.close()

More reference about how to attach files and send it through email,you can find here:https://docs.djangoproject.com/en/2.0/topics/email/ .


This is all about sending email’s in django.

Leave a Comment

Your email address will not be published. Required fields are marked *