send_mail() is Django’s quick path for sending an email through the currently configured email backend. A validated form supplies the message content, while the function receives a subject, message, sender, and recipient list. In development, the backend can print the email to the console instead of delivering it. section 7.1.1 section 7.6
Email a submitted comment
from django.core.mail import send_mail if form.is_valid(): name = form.cleaned_data["name"] comment = form.cleaned_data["comment"] message = f"Received comment from {name}\n\n{comment}" send_mail( "Received comment", message, "admin@example.com", ["admin@example.com"], fail_silently=False, ) After is_valid() creates cleaned_data, the view builds the message and calls send_mail(). Setting fail_silently=False makes delivery problems raise an exception rather than disappearing quietly; the development server reports the problem as a 500 error, while production logs it. section 7.1.1
Listing 7.2 A view accepting both HTTP GET and POST to handle comment form data
# RiffMates/content/views.py
from django.core.mail import send_mail
from django.shortcuts import render, redirect
from content.forms import CommentForm #1
def comment(request):
if request.method == 'GET':
form = CommentForm() #2
else: # POST #3
form = CommentForm(request.POST) #4
if form.is_valid(): #5
name = form.cleaned_data["name"] #6
comment = form.cleaned_data["comment"]
message = f"""\
Received comment from {name}\n\\n
{comment}
"""
send_mail("Received comment", message, #7
"admin@example.com", ["admin@example.com"],
fail_silently=False) #8
return redirect("comment_accepted") #9
# Was a GET, or Form was not valid #10
data = {
"form": form,
}
return render(request, "comment.html", data)
Use the complete view listing to follow the GET-and-POST request flow: display the form, validate submitted data, send the email, and redirect after success. section 7.1.1
