Add Contact Form
NotesGreat, now armed with SMTP settings let’s head back to the code and implement a contact form. Sending email only needs Python’s standard library, so there’s nothing to install.
Add the following settings to config/settings.py:
CONF_MAIL_USERNAME: str = "" # NEW
CONF_MAIL_PASSWORD: str = "" # NEW
CONF_MAIL_SERVER: str = "smtp.example.com" # NEW
CONF_MAIL_PORT: int = 587 # NEW
CONF_MAIL_STARTTLS: bool = True # NEW
CONF_MAIL_FROM: str = "noreply@exampleforyou.net" # NEW
CONF_MAIL_FROM_NAME: str = "ExampleForYou Website" # NEW
CONF_MAIL_CONTACT_TO: str = "hello@exampleforyou.net" # NEW
CONF_MAIL_DEV_MODE: bool = True # NEWCONF_MAIL_FROM must be an address your SMTP service allows you to send from, and CONF_MAIL_CONTACT_TO is where contact form messages are delivered. (The addresses above are only examples.)
Never put secret information in the defaults in settings.py, which ends up in version control. Leave the username and password blank, and set the real values in the .env file instead, as shown below.
We’ll create a separate place to keep the code for sending emails, which can be utilised by numerous aspects of the project. For example, here we’ll be sending messages via the contact form, however we’ll also need to send emails for the user registration flow later. You may find other use cases such as mailing lists.
Create a new directory in the root of the project:
mkdir mailAnother feature here: if you don’t want to be sending real emails during development and testing, the CONF_MAIL_DEV_MODE setting means the message is only printed to the console. It’s on by default, so you have to deliberately turn it off to send real email.
Add the following code:
import smtplib
import ssl
from email.message import EmailMessage
from email.utils import formataddr
from fastapi import HTTPException, status
from config.settings import settings
def send_email_or_500(subject: str, body: str, recipients: list[str],
reply_to: list[str] | None = None) -> None:
# In development, print the email instead of sending it
if settings.CONF_MAIL_DEV_MODE:
print(f"--- Email (dev mode, not sent) ---\n"
f"To: {', '.join(recipients)}\nSubject: {subject}\n\n{body}\n"
f"----------------------------------")
return
message = EmailMessage()
message["Subject"] = subject
message["From"] = formataddr((settings.CONF_MAIL_FROM_NAME, settings.CONF_MAIL_FROM))
message["To"] = ", ".join(recipients)
if reply_to:
message["Reply-To"] = ", ".join(reply_to)
message.set_content(body)
try:
tls = ssl.create_default_context()
if settings.CONF_MAIL_PORT == 465:
# Port 465: the connection is encrypted from the start
smtp = smtplib.SMTP_SSL(settings.CONF_MAIL_SERVER, settings.CONF_MAIL_PORT, context=tls, timeout=10)
else:
# Port 587 (or 25): connect, then upgrade to TLS with STARTTLS
smtp = smtplib.SMTP(settings.CONF_MAIL_SERVER, settings.CONF_MAIL_PORT, timeout=10)
if settings.CONF_MAIL_STARTTLS:
smtp.starttls(context=tls)
with smtp:
if settings.CONF_MAIL_USERNAME:
smtp.login(settings.CONF_MAIL_USERNAME, settings.CONF_MAIL_PASSWORD)
smtp.send_message(message)
except (smtplib.SMTPException, OSError):
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Sorry, the email could not be sent.")send_email_or_500() takes a subject, a body and a list of recipients, plus optional reply-to addresses. In dev mode it prints the email and returns. Otherwise:
EmailMessagebuilds the email.formataddr()makes a “from” address with a display name, likeExampleForYou Website <noreply@exampleforyou.net>.- On port
465it connects withSMTP_SSL, encrypted from the start. On any other port it connects withSMTP, then upgrades to TLS withstarttls().ssl.create_default_context()makes sure the server’s certificate is checked, so the password can’t be intercepted. (CONF_MAIL_STARTTLScan turn STARTTLS off, which is only ever needed for a local test server.) with smtp:closes the connection when done, even if something fails.- If the server can’t be reached, rejects the login or refuses the message,
smtplibraises anSMTPException(or anOSErrorfor network problems), which becomes a500error with a polite message.timeout=10stops a slow server holding up the request forever.
smtplib is synchronous: it waits for the mail server. That’s fine, because the views calling it are plain def functions, which FastAPI runs in its thread pool.
Create a new file for working on the contact view:
from fastapi import APIRouter, Form, Request, status
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from pydantic import EmailStr
from config.settings import settings
from mail.sendmail import send_email_or_500
router = APIRouter()
templates = Jinja2Templates('web/templates')
# Contact Form
@router.get('/contact', response_class=HTMLResponse, status_code=status.HTTP_200_OK)
def contact_get_view(*, request: Request):
context = {
"page": "contact",
}
return templates.TemplateResponse(request, 'contact_form.html', {'context': context})
@router.post('/contact', response_class=HTMLResponse)
def contact_post_view(*,
request: Request,
name: str = Form(...),
email: EmailStr = Form(...),
message: str = Form(...)):
name = " ".join(name.split()) # no line breaks: the name goes in the email's subject line
body = (f"You have a message from {name} <{email}>.\n\n"
f"{message}\n\n"
f"Sent from the contact form at {settings.CONF_MAIN_DOMAIN}")
send_email_or_500(subject=f"Contact form message from {name}",
body=body,
recipients=[settings.CONF_MAIL_CONTACT_TO],
reply_to=[email])
context = {
"page": "contact"
}
return templates.TemplateResponse(request, 'message_sent.html', {'context': context})Let’s break down the code. You should be familiar with the contact_get_view function by now: it simply renders the contact form page from a template (which we’ll add shortly) using the GET method.
Then the contact_post_view function handles the contact form submission using the POST method. It builds the email from the form fields, and sends it to CONF_MAIL_CONTACT_TO using send_email_or_500. A few points:
" ".join(name.split())turns any line breaks in the name into spaces. The name goes into the email’s subject line, and a line break there could add extra email headers (Python’semailmodule refuses such headers anyway, with aValueError).email: EmailStrvalidates the visitor’s email address (using theemail-validatorpackage that comes withfastapi[standard]).reply_to=[email]means that when you press reply in your email client, the reply goes to the visitor. The email itself comes from your ownCONF_MAIL_FROMaddress: sending “from” the visitor’s address would fail the anti-spoofing checks (SPF and DKIM) that email providers use, and the message would be rejected or land in spam.
Add the following templates, one for the contact page and one shown when a message has been sent successfully:
{% extends "_base.html" %}
{% block content %}
<!-- Page Header -->
<header class="intro-header" style="background-image: url('/static/img/contact-bg.jpg')">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<div class="page-heading">
<h1>Contact</h1>
</div>
</div>
</div>
</div>
</header>
<!-- Main Content -->
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<p>Use the form to send a message:</p>
<form action="/contact" method="post">
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Name</label>
<input type="text" class="form-control" placeholder="Name" id="name" name="name"
value="{{ context.name or '' }}" required>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Email</label>
<input type="email" class="form-control" placeholder="Email Address" id="email" name="email"
value="{{ context.email or '' }}" required>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Message</label>
<textarea id="message" class="form-control" placeholder="Message" name="message" rows="4"
required>{{ context.message or '' }}</textarea>
</div>
</div>
<br>
<div class="row">
<div class="form-group col-xs-12">
<button type="submit" class="btn btn-default">Send</button>
</div>
</div>
</form>
{% if context.error_message %}<p><strong>{{ context.error_message }}</strong></p>{% endif %}
</div>
</div>
</div>
<hr>
{% endblock %}{{ context.name or '' }} fills in a field when the form is shown again after an error (covered in the next section), and leaves it empty otherwise.
{% extends "_base.html" %}
{% block content %}
<!-- Page Header -->
<header class="intro-header" style="background-image: url('/static/img/contact-bg.jpg')">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<div class="page-heading">
<h1>Message Sent</h1>
</div>
</div>
</div>
</div>
</header>
<!-- Main Content -->
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<p>You have successfully sent your message.</p>
</div>
</div>
</div>
{% endblock %}Add a link to the contact page in the navigation in _base.html:
<li>
<a href="/contact">Contact</a>
</li>Include the contact view router in main.py:
from web.views import home_view, blog_views, contact_view # UPDATED main_app.include_router(contact_view.router, tags=["web_views"]) # NEWTo send real email, put your SMTP settings in the .env file in the root of the project, and turn dev mode off. pydantic-settings reads this file automatically (see Getting Started), so there’s no need to export or source anything:
CONF_MAIL_SERVER=mail.your-domain.com
CONF_MAIL_PORT=587
CONF_MAIL_USERNAME=your-smtp-username
CONF_MAIL_PASSWORD=your-smtp-password
CONF_MAIL_FROM=noreply@your-domain.com
CONF_MAIL_CONTACT_TO=you@your-domain.com
CONF_MAIL_DEV_MODE=falseAssuming your SMTP settings are valid, running the application should now have a http://localhost:8000/contact page that will send an email as configured.
With CONF_MAIL_DEV_MODE on, the email is written out to the console instead:
--- Email (dev mode, not sent) ---
To: hello@exampleforyou.net
Subject: Contact form message from Jane Doe
You have a message from Jane Doe <jane@example.com>.
Hello there
Sent from the contact form at https://localhost
----------------------------------To see exactly what would be sent, without sending real email, run a local SMTP server that prints every message it receives. aiosmtpd has one built in:
pip install aiosmtpd
python -m aiosmtpd -n -l localhost:1025Then point the application at it, with CONF_MAIL_DEV_MODE=false, CONF_MAIL_SERVER=localhost, CONF_MAIL_PORT=1025 and CONF_MAIL_STARTTLS=false.