Laughing Blog Tutorial Part 3 - Send Alternative Content Type Emails in Django

django

https://www.goodfreephotos.com/

published on: | by cindy In categories: Tutorial Series , Django

In today's tutorial, we extend the newsletter app to include multiple version of email content.

Html emails can be formatted well and include pictures, unlike plain text emails. However, some email clients (mostly older ones) cannot read html. Therefore It may be useful to send plain text emails a alongside html email because we want all our subscribers receiving their emails.

To achieve sending multiple email content, we are going to use Django email library called EmailMultiAlternatives. For a much cleaner code, we will create a function.

We will also cover django message framework to display user notifications Instead of printing notification to console see documentation

Let's get started!

Create a new file on newsletter app and name it emails.py.

def send_multiple_email(name, receiver):
    subject = 'Welcome to Laughing Blog Tutorial'
    sender = 'test@achiengcindy.com'
    text_template = render_to_string(
        'newsletter/email-subscribe.txt', {'name': name})
    html_template = render_to_string(
        'newsletter/email-subscribe.html', {'name': name})
    message = EmailMultiAlternatives(
        subject, text_template, sender, [receiver])
    message.attach_alternative(html_template, 'text/html')
    message.send()

In the above code, we created a function send_multiple_email taking two parameters. Define the subject of the email and sender. Use the render_to_string function and pass the templates for the email body.

We can now create the email template

newsletter/templates/email-subscribe.html

<h2>Hello {{name}}</h2> 
Welcome to Laughing Blog Newsletter and thank you for signing up. 
You will find the most exciting news about Python, Django, Programming tips and web development tools that will go along way to see you grow your skills

newsletter/templates/email-subscribe.txt

Hello {{name}}
Welcome to Laughing Blog  Newsletter and thank you for signing up. 
You will find the most exciting news about Python, Django,Programming tips and web development tools that will go along way to see you grow your skills

Now is a good time to make a few changes in views.py.Change your views to look like this:

newsletter/views.py

def newsletter_subscribe(request):
    if request.method == 'POST':
        form = NewsUserForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            # we dont want to save just yet
            if NewsUsers.objects.filter(email=instance.email).exists():
                print('your email Already exists in our database')
            else:
                instance.save()
                print('your email has been submitted to our database')
                send_multiple_email(instance.name, instance.email)
    else:
        form = NewsUserForm()
    context = {'form': form}
    template = 'newsletter/subscribe.html'
    return render(request, template, context)

First ,import the function we just created

from .emails import send_multiple_email
Then instead of send_mail call send_multiple_email Run Server and test

Django messages Framework

Edit your views with the following: First import messages framework

from django.contrib import messages 
and next replace these line of codes

print('your email Already exists in our database') 
print('your email has been submitted to our database') 

with these lines respectively python messages.warning(request, 'your Email Already exists in our database') messages.success(request, 'your Email has been submitted to our database')

To display messages edit subscription template to look like this:

<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif    %}>{{ message }</li>
{% endfor %}
</ul>
{% else %}
<form action="{% url 'newsletter:subscribe' %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
{% endif %}

Conclusion

We are now able to send alternative emails and have a more readable code.The source code for this tutorial is available on Github .

Connect with me on Twitter