Sending Emails with Django

  • Sending Emails with Django is pretty straightforward. 1st, you need to have a local SMTP(Simple Mail Transfer Protocol) server, or you need to define the configuration of an external SMTP server by adding the following settings to the settings.py file of your project:
    • EMAIL_HOST: The SMTP server host; the default is localhost.
    • EMAIL_PORT: The SMTP port; the default is 25.
    • EMAIL_HOST_USER: The username for the SMTP server.
    • EMAIL_HOST_PASSWORD: The password for the SMTP server.
    • EMAIL_USE_TLS: Whether to use a TLS(Transport Layer Security) secure connection.
    • EMAIL_USE_SSL: Whether to use an implicit TLS secure connection.
  • If we can not use an SMTP server, we can tell Django to write emails to the console by adding the following setting to the settings.py file
    • EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
  • By using this setting, Django will output all emails to the shell. This is very useful for testing your application without an SMTP server.
  • If we want to send emails but you don't have a local SMTP server, we can probably use the SMTP server of our email service provider. 
  • The below sample configuration is valid for sending emails via Gmail Servers using a Google account:
    • EMAIL_HOST = 'smtp.gmail.com'
    • EMAIL_HOST_USER = 'your_email_account@xx.com'
    • EMAIL_HOST_PASSWORD = 'xx_password'
    • EMAIL_PORT = 587
    • EMAIL_USE_TLS = True
  • Run the python manage.py shell command to open the Python shell and send an email, as follows:
    • from django.core.mail import send_mail
    • send_mail('Python Django Email', 'This Sample E-mail was sent with Django.', 'your_email_account@gmail.com', ['your_email_account@gmail.com'], fail_silently=False)
  • The send_mail() function takes the subject, message, sender, and list of recipients as required arguments. 
  • By setting the optional argument fail_silently=False, you are telling it to raise an exception if the email couldn't be sent correctly. 
  • If you are sending emails using Gmail with the preceding configuration, you will have to enable access for less secure applications at https://myaccount.google.com/lesssecureapps, as follow
  • Some times you may also have to disable Gmail captcha at https://accounts.google.com/displayunlockcaptcha in order to send emails with Django.
  • Edit the posts_share view in the views.py file of the xx application, as follows:
from django.core.mail import send_mail
def posts_share(request, post_id):
    # Retrieve post by id
    post = get_object_or_404(Posts, id=post_id, status='published')
    sent_email = False
    if request.method == 'POST':
        # Form was submitted
        form = EmailPostForm(request.POST)
        if form.is_valid():
            # Form fields passed validation
            cd = form.cleaned_data
            post_url = request.build_absolute_uri(post.get_absolute_url())
            subject = f"{cd['name']} recommends you read " f"{post.title}"
            message = f"Read {post.title} at {post_url}\n\n" f"{cd['name']}\'s comments: {cd['comments']}"
            send_mail(subject, message, 'xx@xx.com', [cd['to']])
            sent_email = True
        else:
            form = EmailPostForm()
            return render(request, 'xx/posts/share.html', {'post': post,'form': form,'sent': sent_email })

  • In the code above you declare a sent_email variable and set it to True when the post was sent. You will use that variable later in the template to display a success message when the form is successfully submitted.
  • Since you have to include a link to the post in the email, you retrieve the absolute path of the post using its get_absolute_url() method. 
  • You use this path as an input for request.build_absolute_uri() to build a complete URL, including the HTTP schema and hostname. 
  • You build the subject and the message body of the ';email using the cleaned data of the validated form and, finally, send the email to the email address contained in the to field of the form.

Comments

Popular posts from this blog

Internationalization (Language Setting) in Django

reverse_lazy() Method in Django

CharFilter in Django