Skip to content

About

Form API in charge of sending forms by email

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

formsender

formsender is a contact-form processing backend that allow to implement and process forms from static websites.

It receives HTML form submissions over a small REST/JSON API, validates and sends them by email.

Emails are sent asynchronously through an RQ queue backed by Redis.

Why you should use formsender?

  • You need to process form from static websites
  • formsender is easy to setup and database-less
  • you appreciate that both you and your visitor receive a copy the data filled in the form
  • you like tools helping your integration work like test, examples, ready-to-use JS and HTML code
  • you want to avoid spam bots.

Features included in formsender:

  • multiple forms setup

  • mutilple SMTP relay setup

  • easy YAML-based configuration

  • ready-to-use view and test interface

  • simple docker-based deployment

  • sync/async modes for developmet and production deployment

  • no database need

  • easy email templating straight in the YAML config file

  • support for static resources serve (for email design or other usage)

  • live HTML interface to test and try form

  • honeypot mechanism to prevent spam bots

  • parametric recipients: the end user + a series of cc/bcc

  • optionnal and required fields

  • python 3.13 or +

  • docker based deployment.

  • Stack: Python 3.13, Flask, RQ, Redis, Jinja2, gunicorn, Docker.

  • Deployment: one Docker image. The code and forms.yml are mounted from the host, so the same image serves production and development.


1. Installation and running

Prerequisites

  • Docker with the Compose plugin
  • An SMTP server
  • Apache (or another reverse proxy) in front of the service, for HTTPS

Steps

cd /path/to/formsender
cp forms.yml.tmpl forms.yml          # edit your forms
cp smtp.yml.tmpl smtp.yml            # edit your SMTP relays
cp docker-compose.yml.tmpl docker-compose.yml
cp .env.tmpl .env                    # edit SMTP passwords and paths
sudo mkdir -p /var/log/formsender && sudo chown "$USER" /var/log/formsender
docker compose up -d --build
docker compose logs -f app

The service listens on 127.0.0.1:8000. Put the Apache reverse proxy from section 7 in front of it.

Check the forms file at any time:

docker compose exec app flask check-forms-config

Development mode

Set DEBUG=True in .env and restart:

docker compose up -d

In this mode gunicorn reloads when a file under src/ changes, and the RQ worker restarts on the same changes. It is not for production. Also, forms.yml is read on every request, so edits to it take effect immediately.

Production mode

Keep DEBUG=False (the default). gunicorn runs with two workers and the RQ worker runs once; neither reloads on file changes.

Updating

Pull the new code into FORMSENDER_CODE_DIR, then run docker compose up -d --build. Because the code is mounted, a code-only change needs only a restart: docker compose restart app.


2. Configuration

Global settings: environment variables

All global settings come from environment variables. Set them in .env.

Variable Default Description
DEBUG False True enables development mode (auto-reload, detailed errors).
TEST_IT_TOKEN empty Token that unlocks the /forms/<slug>/test-it preview page. Empty disables the page (every request gets 403).
SMTP_CONFIG_PATH /config/smtp.yml Path to the SMTP relays file inside the container.
SMTP_PASSWORD_<NAME> empty Passwords for the relays, referenced by password_env in smtp.yml.
PUBLIC_BASE_URL (required) Public URL of the service through the front end, e.g. https://forms.domain.tld. Used in the generated JavaScript.
REDIS_URL redis://redis:6379/0 Redis connection for the RQ queue.
FORMS_FILE_PATH /config/forms.yml Path to the forms file inside the container.
STATIC_FOLDER_PATH empty Folder served under /static/ (e.g. images). Empty disables it.
SENDINGS_LOG_PATH /var/log/formsender/sendings.log Log file where the worker records each email sent or failed.

Boolean values accept True/False, true/false, 1/0, yes/no, on/off.

Previewing emails: /forms/<slug>/test-it

GET /forms/<slug>/test-it?token=<TEST_IT_TOKEN> opens a three-column test screen:

  • Left: the form fields, then a View button, a checkbox "Also send to form recipient", and a Test button.
  • Centre: the rendered email. View renders it again (it also refreshes while you type). Viewing never sends anything.
  • Right: the form parameters, a Placeholders list (each one has a Copy button, e.g. {{ my_field_slug }} and {{ FIELDS }}), then the raw subject and text/HTML templates, unrendered.

Test really sends the team copy (to send_to and bcc_to), through the form's SMTP relay. With the checkbox ticked, it also sends the submitter email to the address typed in the form recipient field. Sends are logged in sendings.log with a test prefix. The preview itself never sends anything. A missing or wrong token gets HTTP 403. Keep TEST_IT_TOKEN secret, or leave it empty to turn the page off.

Working on a form with its test URL

The test page is the quickest way to create or change a form. Edit the files, reload the page, check the result, and send a real test email when you are happy with it.

1. Get the URL. Run list-forms (see Command reference):

docker compose exec app flask list-forms

Each line gives the form's test page: https://forms.domain.tld/forms/<slug>/test-it?token=<TEST_IT_TOKEN>. Open it in a browser. Locally, the same page is at http://127.0.0.1:5000/forms/<slug>/test-it?token=... (the port from docker-compose.yml), because list-forms prints the public base URL.

2. Read the page.

  • Left: the form's fields (* marks required ones), View, the "Also send to form recipient" checkbox, and Test.
  • Centre: the rendered email.
  • Right: the form parameters (from forms.yml, and the relay's from address from smtp.yml), the placeholders (each with a Copy button), and the raw subject, text and HTML templates and signatures.

3. Write the template. Click Copy next to a placeholder such as {{ my_field_slug }} or {{ FIELDS }} and paste it into email_template in forms.yml.

4. Check it. Enter sample values and click View. The centre column updates, and the raw templates on the right show what you wrote. Nothing is sent.

5. Change and reload. forms.yml and smtp.yml are read on every request. After you save them, reload the test page: no container restart is needed. Changes to .env (passwords, TEST_IT_TOKEN) need docker compose up -d.

6. Send a real test. Click Test. It sends the team copy to send_to and bcc_to. Tick "Also send to form recipient" to also send the submitter email to the address you entered in the form's recipient field. The result of each email (sent, failed or skipped, with the error) appears under the buttons. Test emails are logged in sendings.log with a test prefix.

Tips

  • A form with mode: sync delivers in the request, so a failing relay shows up as a 500 in the browser. Use it while you debug a relay. Use mode: async in production.
  • Run flask check-smtp-connections first if Test fails, to tell a wrong password from a network problem.

Security of the test URL

  • The token is the only protection. Anyone with the URL can send emails through your relays with Test. Keep the URL private, and do not paste list-forms output into a shared place.
  • Apache logs the query string (combined log format), so the token is written to forms.domain.tld-access.log. Restrict who can read that file.
  • To rotate the token, change TEST_IT_TOKEN in .env, run docker compose up -d, and run list-forms again. The old URLs then return 403.
  • Apache forwards every path, so the page is reachable from the internet. If you only use it from your office, restrict /forms/*/test-it in the virtual host (for example with Require ip), and check the change with apachectl configtest.

SMTP relays: smtp.yml

The file is a list of SMTP relays. Each form picks one with smtp_relay: <name>, so forms can send from different accounts, relays and From: addresses while sharing one formsender instance. Passwords are not written in this file: password_env names the variable in .env that holds the password.

- name: default
  host: smtp.example.com
  port: 587
  starttls: true
  username: noreply@example.com
  password_env: SMTP_PASSWORD_DEFAULT
  from_address: noreply@example.com
Property Required Default Description
name yes Unique name, referenced from forms.yml.
host yes SMTP server host name.
from_address yes Sender address used in From: for every email sent through this relay.
port no 587 SMTP server port. Use 465 with starttls: false for implicit TLS.
starttls no true Upgrade the connection with STARTTLS.
username no empty SMTP login. Leave empty if the server needs no authentication.
password_env no empty Name of the environment variable holding the password.

flask check-forms-config checks that every form names an existing relay, that every password_env variable is set, and that every from_address is a valid address.

Forms: forms.yml

The file is a list of forms. Each form needs a unique slug.

- slug: demo_contact
  mode: async
  label: Demande de démo
  send_to_label: Domain Sales Team
  send_to:
    - sales@domain.tld
  bcc_to:
    - sales@domain.tld
  send_to_field_slug: email
  domains:
    - https://www.website.tld
  honeypot: website
  fields:
    - slug: name
      label: Nom
      required: true
      type: text
  email_template:
    subject: "Merci {{ name }}"
    text_body: |
      Bonjour {{ name }},
      {{ FIELDS }}
    html_body: |
      <h1>Bonjour {{ name }}</h1>
      {{ FIELDS }}

See forms.yml.tmpl for a complete example.

Form properties

Property Required Default Description
slug yes Unique identifier, used in URLs.
smtp_relay yes Name of a relay in smtp.yml. Its from_address and credentials are used to send this form's emails.
mode yes async queues the delivery to the worker (production). sync sends the emails during the request, so errors show up in the response (useful for testing). Must be set explicitly.
domains yes Origins allowed to post, e.g. https://www.website.tld. Use '*' to allow any origin.
label no empty Human-readable name, shown in the generated HTML and in the team copy subject.
fields no [] List of fields (see below).
send_to no [] Team recipients. They receive the team copy.
bcc_to no [] Hidden team recipients. They receive the team copy.
send_to_label no empty Display name for the team recipients.
send_to_field_slug no empty Name of a field whose value is the submitter's address. If the value is set, the submitter receives email_template.
honeypot no empty Slug of a field used as an anti-bot trap (see Honeypot).
email_template no empty Email content (see Email templates).

Field properties

Property Required Default Description
slug yes Unique within the form. Used as the field name in the HTML and the JSON.
label no empty Label shown to the user and in emails. Falls back to slug when empty.
required no false If true, an empty value is rejected.
type no text text, multiline-text or checkbox. A checkbox is sent as checked or not-checked, even when unticked.
required_value yes for a required checkbox, otherwise no empty Checkbox only, used with required: true: checked (the box must be ticked) or not-checked (it must stay unticked). Unquoted true/false are not accepted.
help no empty Help text shown under the input in the generated HTML.

Constraints checked by flask check-forms-config:

  • Form slugs are unique. Field slugs are unique within a form.
  • domains lists at least one origin or '*'.
  • send_to_field_slug and honeypot match an existing field.
  • The honeypot field is not required.
  • Addresses in send_to and bcc_to are valid email addresses.
  • type is a supported type.
  • A required checkbox has a required_value, which is checked or not-checked. required_value is only allowed on a checkbox, and only with required: true.

Email templates

email_template is optional. Without it, the submitter gets nothing and the team copy uses the default body.

Template properties

Property Required Default Description
subject no empty Email subject. Plain text, with placeholders. Line breaks are removed.
text_body no none Text part. Dedented, so it can be indented in the YAML. If absent, the text part is left out.
html_body no none HTML part. Placeholder values are HTML-escaped. If absent, the HTML part is left out.
text_signature no none Signature for the text part (and for the HTML part if html_signature is absent).
html_signature no none Signature for the HTML part (and for the text part if text_signature is absent).

Placeholders

Placeholder Where Renders as
{{ slug }} subject, text_body, html_body The value of that field. Unknown slugs render as empty text.
{{ FIELDS }} text_body One line per visible field: - Label: answer.
{{ FIELDS }} html_body <ul><li>Label: <b>answer</b></li>…</ul>.

Signatures are not rendered: {{ }} stays as written, and a leading -- line is kept.

Signatures

Defined Text part HTML part
both text_signature html_signature
only text_signature text_signature text_signature, escaped, in <pre class="moz-signature" cols="72">
only html_signature html_signature converted to plain text (tags removed, block tags become line breaks) html_signature as is

Signatures are optional and independent of the bodies. Use text_signature alone for plain text.

  email_template:
    subject: "Merci {{ name }} pour votre demande"
    text_body: |
      Bonjour {{ name }},

      Merci pour votre demande.

      Récapitulatif :
      {{ FIELDS }}
    text_signature: |
      -- 
      Jack ROBIN - Sales manager
      Email : jack@domain.tld
      Tél. (+01) 999 888 777
      https://www.domain.tld
  email_template:
    subject: "Merci {{ name }} pour votre demande"
    text_body: |
      Bonjour {{ name }},
      {{ FIELDS }}
    html_body: |
      <p>Bonjour {{ name }},</p>
      {{ FIELDS }}
    text_signature: |
      Jack ROBIN - Sales manager
      Email : jack@domain.tld
    html_signature: |
      <p><b>Jack ROBIN</b> - Sales manager<br>
      <a href="mailto:jack@domain.tld">jack@domain.tld</a></p>

Which email gets what

Email Sent when Recipients Subject
Submitter send_to_field_slug is set, the field has a value, and email_template exists The field's value subject
Team copy send_to or bcc_to is not empty send_to, and bcc_to as hidden recipients [COPY] + subject. Without email_template: [COPY] + the form label

The team copy starts with the line THIS EMAIL IS A COPY OF THE MESSAGE SENT TO THE USER. (text), and the same text in an orange box (HTML). Without email_template, its body is the list of fields.

Honeypot

A honeypot is a field that real users never see but bots fill in.

  1. Declare one field and name it in the form: honeypot: website.
  2. The generated HTML hides it (display: none), so humans leave it empty.
  3. If the value is not empty, the API returns HTTP 200, sends nothing and does not reveal the check.

The honeypot field is not listed in emails.

Domains and cross-site requests

Browsers send an Origin header on cross-site requests. For each form:

  • If domains contains '*', any origin is accepted.
  • Otherwise the Origin must match an entry in domains, or the request gets HTTP 403.
  • A request with no Origin header (server-to-server calls, curl) is refused with 403 unless '*' is in domains.

The OPTIONS preflight request returns the CORS headers.

Note: CORS headers only control what browsers allow. The server checks Origin itself, so the check still applies to requests made with other tools.


3. API

All request and response bodies are JSON, except the HTML and JavaScript routes.

Method Route Description
GET /forms/<slug> Form structure as JSON.
GET /forms/<slug>/html A raw <form> element, ready to include in a page.
GET /forms/<slug>/js JavaScript with a postForm(form) function.
POST /forms/<slug>/entry Submit a form.
OPTIONS /forms/<slug>/entry CORS preflight.
GET /static/<path> Files from STATIC_FOLDER_PATH.

Submit a form

curl -i -X POST https://forms.domain.tld/forms/demo_contact/entry \
  -H 'Content-Type: application/json' \
  -H 'Origin: https://www.website.tld' \
  -d '{"name": "Ada", "email": "ada@example.com", "phone": "0123456789"}'

Responses:

  • 200 {"status": "accepted"}: validated and queued. Emails are sent later by the worker. A filled honeypot also returns 200.
  • 400 {"errors": ["'Nom' is required", ...]}: validation failed.
  • 403 {"errors": ["Origin not allowed for this form."]}: origin refused.
  • 404: unknown form.

Unknown fields are ignored. Values must be text; null is treated as empty.


4. Using the form on your website

Generate the JavaScript once:

docker compose exec app flask get-js-post-form demo_contact > postform.js

Include it in your page, then call it from a button:

<script src="postform.js"></script>
<form>
  <input name="name" placeholder="Nom" required>
  <input name="email" placeholder="Email" required>
  <input type="button" value="Envoyer" onclick="postForm(this.form)">
</form>

Or generate the whole HTML form: GET /forms/demo_contact/html. postForm shows an alert on success or error. Customize the messages in the generated code, which is intentionally simple.


5. Command reference

Run these inside the container, e.g. docker compose exec app flask <command>.

Command Description
flask check-forms-config Validate forms.yml and smtp.yml and list every problem. Exit code 1 on error.
flask list-forms List every form with its /test-it URL (includes the token, see warning below).
flask list-smtp-relays List every SMTP relay with its host, port, STARTTLS setting, username and from address. Passwords are not shown.
flask check-smtp-connections Connect to each SMTP relay (STARTTLS, then login if it has a username) and report the server's answer. Sends no email.
flask get-js-post-form <slug> Print the postForm JavaScript for one form.

check-forms-config

Checks forms.yml and smtp.yml together: every form has a valid mode, a smtp_relay that exists, and every relay's password_env variable is set. It prints the number of forms and relays when everything is valid, and one ERROR: line per problem otherwise (exit code 1).

docker compose exec app flask check-forms-config

list-forms

Prints one line per form, with the URL of its test page:

List of forms:

- demo_contact → https://forms.domain.tld/forms/demo_contact/test-it?token=...

Warning: the URL contains TEST_IT_TOKEN in clear text. Do not paste this output into a ticket, a chat or a shared log.

list-smtp-relays

Prints one line per relay from smtp.yml:

List of SMTP relays:

- default		 Params: HOST=smtp.example.com, PORT=587, StartTLS=True, USERNAME=noreply@example.com, FROM=noreply@example.com

check-smtp-connections

Tests each relay from smtp.yml in turn, and prints the server's answer for each one (for a relay with a username, the answer to the login, e.g. a 235 code on success). Use it after changing credentials, or when emails stop being delivered, to tell a bad password from a network problem. It only connects and logs in: no email is sent.

docker compose exec app flask check-smtp-connections

If a relay cannot be reached or rejects the login, the command stops with the Python error (for example SMTPAuthenticationError) and the relays after it are not tested.

get-js-post-form

docker compose exec app flask get-js-post-form demo_contact > postform.js

6. Sendings log

The worker appends one line per email to SENDINGS_LOG_PATH (default /var/log/formsender/sendings.log, mounted from FORMSENDER_LOG_HOST_DIR on the host):

2026-11-24T12:00:00+00:00 | form=demo_contact | kind=submitter | status=sent | to=ada@example.com | subject=Merci Ada
2026-11-24T12:00:00+00:00 | form=demo_contact | kind=team copy | status=failed | to=sales@domain.tld | subject=[COPY] Merci Ada | error=timeout

A failed email is logged with status=failed and the job is marked as failed in RQ. formsender does not retry automatically.


7. Apache configuration

Apache terminates HTTPS, forwards requests to 127.0.0.1:8000, and applies request rate limits.

Enable the modules first:

sudo a2enmod ssl proxy proxy_http headers qos

Then /etc/apache2/sites-available/forms.domain.tld.conf:

<VirtualHost *:80>
    ServerName forms.domain.tld
    RewriteEngine On
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</VirtualHost>

<VirtualHost *:443>
    ServerName forms.domain.tld

    SSLEngine on
    SSLCertificateFile    /etc/letsencrypt/live/forms.domain.tld/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/forms.domain.tld/privkey.pem

    # Rate limiting (mod_qos). Limit requests per client IP.
    <IfModule mod_qos.c>
        QS_ClientEventPerSecLimit 10
        QS_ClientEventBlockCount 100 900
    </IfModule>

    ProxyPreserveHost On
    ProxyPass        /static/ http://127.0.0.1:8000/static/
    ProxyPassReverse /static/ http://127.0.0.1:8000/static/
    ProxyPass        /        http://127.0.0.1:8000/
    ProxyPassReverse /        http://127.0.0.1:8000/

    ErrorLog  ${APACHE_LOG_DIR}/forms.domain.tld-error.log
    CustomLog ${APACHE_LOG_DIR}/forms.domain.tld-access.log combined
</VirtualHost>

Enable and reload:

sudo a2ensite forms.domain.tld
sudo apachectl configtest && sudo systemctl reload apache2

Notes:

  • The app does not set CORS headers for the proxy. It sets them itself, so no Header directives are needed.
  • The mod_qos directive names depend on the mod_qos version. Check them with apachectl configtest, and adjust the thresholds to your traffic.
  • Set PUBLIC_BASE_URL to https://forms.domain.tld so the generated JavaScript points to the public URL.

8. Tests

python3.13 -m venv .venv
.venv/bin/python -m pip install -r requirements-dev.txt
.venv/bin/python -m pytest

The tests use fakeredis and a mocked SMTP connection; no Redis or SMTP server is needed.


9. Project layout

src/formsender/
├── __init__.py     # create_app()
├── config.py       # Settings, read from environment variables
├── models.py       # Form, Field, EmailTemplate
├── loader.py       # reads and validates forms.yml and smtp.yml
├── validation.py   # checks a submission against its form
├── rendering.py    # email bodies, HTML form, JavaScript
├── mailer.py       # builds the submitter email and the team copy, sends over SMTP
├── sendings_log.py # human-readable sending log
├── tasks.py        # RQ job: delivers one submission
├── views.py        # HTTP routes, CORS, honeypot
└── cli.py          # flask check-forms-config, list-forms, list-smtp-relays, check-smtp-connections, get-js-post-form
tests/              # pytest suite
docker/             # Dockerfile, entrypoint, supervisord configs

10. Troubleshooting

Symptom Check
Container exits at start docker compose logs app. Usually a missing required variable (PUBLIC_BASE_URL), or an invalid forms.yml or smtp.yml (run flask check-forms-config).
500 on every form route docker compose exec app flask check-forms-config.
403 from the browser The page's origin is not in the form's domains.
No email received Read sendings.log. Check the relay's credentials, starttls and password_env.
Code change has no effect In production mode, restart: docker compose restart app.

About

Form API in charge of sending forms by email

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages