官术网_书友最值得收藏!

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 = 'your_account@gmail.com'
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.', 'your_account@gmail.com', ['your_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, 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 {}\n\n{}\'s comments: {}'.format(post.title, post_url, cd['name'], cd['comments'])
send_mail(subject, message, 'admin@myblog.com',
[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'),
]
主站蜘蛛池模板: 镇赉县| 合作市| 长葛市| 宁陕县| 祁阳县| 阿勒泰市| 呼伦贝尔市| 临沧市| 房山区| 涞源县| 白银市| 山西省| 仪征市| 灵璧县| 赣榆县| 福州市| 屏南县| 奇台县| 格尔木市| 达孜县| 滕州市| 巴彦县| 平江县| 渭南市| 金溪县| 鲜城| 隆子县| 九台市| 莱州市| 桦甸市| 黄骅市| 贵溪市| 略阳县| 普兰县| 上思县| 金塔县| 五台县| 黄山市| 镇平县| 龙门县| 金湖县|