How to do it...

To complete this recipe, execute the following two steps:

  1. From Django, import the function in order to send an email. Then, add the save() method to MessageForm. It will try to send an email to the selected recipient and will fail silently if any errors occur:
# email_messages/forms.py 
from django import forms
from django.contrib.auth.models import User
from django.core.mail import send_mail
from django.utils.translation import ugettext_lazy as _


class MessageForm(forms.Form):
# ...

def save(self):
cleaned_data = self.cleaned_data
user = self.request.user
send_mail(subject=_(f"A message from {user}"),
message=cleaned_data["message"],
from_email=self.request.user.email,
recipient_list=[cleaned_data["recipient"].email],
fail_silently=True)
  1. Call the save() method from the form in the view if the posted data is valid:
# email_messages/views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect

from .forms import MessageForm


@login_required
def message_to_user(request):
if request.method == "POST":
form = MessageForm(request, data=request.POST)
if form.is_valid():
form.save()
return redirect("message_to_user_done")
else:
form = MessageForm(request)

return render(request,
"email_messages/message_to_user.html",
{"form": form})
..................Content has been hidden....................

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