Sending emails with Django

Sending emails with Django is pretty straightforward. First, you will need to have a local SMTP server or define the configuration of an external SMTP server by adding the following settings in 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: Username for the SMTP server
  • EMAIL_HOST_PASSWORD: Password for the SMTP server
  • EMAIL_USE_TLS: Whether to use a TLS secure connection
  • EMAIL_USE_SSL: Whether to use an implicit TLS secure connection

If you cannot use an SMTP server, you 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 you want to send emails, but you don't have a local SMTP server, you can probably use the SMTP server of your email service provider. The following sample configuration is valid for sending emails via Gmail servers using a Google account:

EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'your_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('Django mail', 'This e-mail was sent with Django.', '[email protected]', ['[email protected]'], 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, we are telling it to raise an exception if the email couldn't be sent correctly. If the output you see is 1, then your email was successfully sent.

If you are sending emails by Gmail with the preceding configuration, you might have to enable access for less secured apps at https://myaccount.google.com/lesssecureapps, as follows:

Now, we will add this functionality to our view.

Edit the post_share view in the views.py file of the blog application as follows:

from django.core.mail import send_mail

def post_share(request, post_id):
# Retrieve post by id
post = get_object_or_404(Post, id=post_id, status='published')
sent = 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 = '{} ({}) recommends you reading "
{}"'.format(cd['name'], cd['email'], post.title)

message = 'Read "{}" at {} {}'s comments: {}'.format(post.title, post_url, cd['name'], cd['comments'])
send_mail(subject, message, '[email protected]',
[cd['to']])
sent = True
else:
form = EmailPostForm()
return render(request, 'blog/post/share.html', {'post': post,
'form': form,
'sent': sent})

We declare a sent variable and set it to True when the post was sent. We will use that variable later in the template to display a success message when the form is successfully submitted. Since we have to include a link to the post in the email, we will retrieve the absolute path of the post using its get_absolute_url() method. We use this path as an input for request.build_absolute_uri() to build a complete URL, including HTTP schema and hostname. We 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.

Now that your view is complete, remember to add a new URL pattern for it. Open the urls.py file of your blog application and add the post_share URL pattern, as follows:

urlpatterns = [
# ...
path('<int:post_id>/share/',
views.post_share, name='post_share'),
]
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.152.87