Email Form Handler

A server-side PHP script to send emails when a form is submitted. Works in tandem with frontend script to provide a seamless experience.


What is it?

This script takes the user's form inputs and sends the details in a templated HTML email to the site admin, and optionally a confirmation email to the user.

Data from your form is submitted to this script, which is then processed and sent via the Swiftmailer email library.

We've taken the hard work out of setting up contact forms. By configuring settings in the forms/smtp.php file you can easily send rich emails to the site owner and user alike.

Forms can be protected by Google reCAPTCHA v2 (Checkbox and Invisible reCAPTCHA). See our reCAPTCHA docs for more detail.

The script returns JSON data to interface with the form javascript on the browser side.

Features
  • Swiftmailer Library
  • SMTP with optional TLS/SSL
  • reCAPTCHA
  • Plain Text + HTML included in emails
  • Save submissions to CSV file
  • HTML templated email to site owner
  • HTML templated confirmation message to user
  • JSON response to interface with form scripts provided with theme.

Requirements

To use the smtp.php form handler you will need the following;

  • An email account from which to send the email
  • SMTP server details for the email account
  • A PHP server > 5.4
  • Configuration of settings in forms/smtp.php

How it Works

When your user submits a form:

  • The input is passed to smtp.php.
  • User's input is processed.
  • Inputs are inserted into an HTML template.
  • An email is constructed from the template.
  • Your web server uses Swiftmailer library to connect to an SMTP server and send an email to the specified address.
  • Optionally a templated HTML email can be sent to the user as confirmation.
  • Optionally the submission data can be saved to a CSV file.
  • Success/error feedback is passed back to the browser as JSON.

Choosing a Sending Server

Set up a new email account on a reliable SMTP server to handle sending emails.

We recommend using an SMTP server associated with your hosting account if possible. This is to minimise any potential communication issues between the web server and the SMTP server.

Some SMTP servers are difficult to work with. We don't recommend using Gmail as your sending server for the following reasons:

  • Gmail servers are particular about security, and you will need to make adjustments in your account's security settings in order to send the email from a Gmail account.
  • If you use two-factor authentication with your Google account, a Single App Password will need to be used.
  • Gmail will refuse to connect to some host's web servers - such as GoDaddy. This may be because the shared hosting server's IP address is blacklisted by Gmail for historical spamming offences.

Configuring settings in smtp.php

All email settings are contained in forms/smtp.php.

Configuration takes the form of PHP variable declaration. All of the variables are already set up with dummy data.

Change the values on the right hand side of the = sign leaving the quotes intact. Values such as true, false and null should not have quotes.

All settings are required.

Server Connection Settings
Variable Description
$outgoingServerAddress Hostname or IP address of the sending server to use.
$outgoingServerPort Port number used to connect to SMTP server. Usually "25" or "587".
$outgoingServerSecurity Security protocol configured on your SMTP server. Supported types are "ssl", "tls" or null.
Sending Account Settings
Variable Description
$sendingAccountUsername Username for the email account that will send the email. Often this is the email address itself.
$sendingAccountPassword Password for the sending account.
Admin Recipient Settings
Variable Description
$recipientEmail Email address of the intended recipient - usually the site owner or admin.
$recipientName The name for the To: field of the email.
Email to Admin Settings
Variable Description
$emailSubject Subject of the email that the admin will see.
$websiteName Used as the From: name on the email.
$adminEmailTemplate Filename of the template to be used for the admin email. Must be a file in the templates folder see Admin Email Template section below.
Feedback Settings
Variable Description
$successMessage Message to be shown to user when form submission was successfully received and email was successfully sent.
reCAPTCHA Settings
Variable Description
$recaptchaSecretKey Optional. If your form contains a reCAPTCHA widget, or uses invisible reCAPTCHA, place your secret key here. See reCAPTCHA documentation for more detail.
$recaptchaErrorMessage Optional. If using reCAPTCHA, this is an explanation to the user for when a reCAPTCHA error occurs.
Confirmation Email Settings
Variable Description
$sendConfirmationToUser Enable or disable confirmation email to the user. Accepts true or false.
$userEmailField Name of the form field which captured the user's email address. Usually "email" or "contact-email"
$userNameField Name of the form field which captured the user's name.
$confirmationEmailTemplate Filename of the template to be used for the confirmation email. Must be a file in the templates folder see Admin Email Template section below.
$confirmationSubject Subject of the confirmation email.
$confirmationFromName Used in the From: field of the confirmation email.
$confirmationReplyTo Input an email address. If the user hits Reply on the confirmation email, this is the address where the reply will be sent.
$confirmationReplacements Please see Confirmation Email Template section below.
CSV Settings
Variable Description
$saveToCSV Enable or disable saving user input to CSV file. Accepts true or false.
$saveToCSVFileName A relative path to a file where the CSV data should be stored eg. "csv/csv_forms_email_1.csv" saves in forms/csv folder. If the file does not exist, it will be created.

Admin Email Template

Located in the forms/templates/email_to_admin.html file is a basic HTML template used as the default content for the email sent out to the site owner.

Templates must be located in the templates folder, and you may edit the template however you see fit.

The admin template has access to the $_POST variable only. This is the form data sent from the user to the server.

Output form data to the email template using tags with double square brackets, which are replaced with the text from the corresponding form input:

User's email address: [[contact-email]]

outputs:

User's email address: user@domain.com

Square brackets must not contain spaces, and must match the name of a form input on the page.

Any other text in the template is output as normal. The template should contain valid HTML compatible with an email reader app.

The text version of the email will contain a basic readout of the user's inputs listed by name of the input field.

Confirmation Email Template

Located in the forms/templates/confirmation_to_user.html file is a basic HTML template. This is used as the default content for the confirmation email sent to the user.

Templates must be located in the templates folder, and you may edit the template however you see fit.

Data for the confirmation template is specified in the $confirmationReplacements array in smtp.php. In the resulting email, the text provided in each key of the array (left of the => arrow) will be replaced by its value (right side of the => arrow).

Include dynamic data in the email by inserting the tags from the $confirmationReplacements keys where necessary in the template.

This example shows how the text [[contact-email]] and [[webAddress]] will be replaced by values in the array.

// array specified in smtp.php
$confirmationReplacements  = array( 
    "[[contact-email]]"  => $_POST["contact-email"],
    "[[webAddress]]"     => 'http://mrare.co',
);


// Template text in forms/templates/confirmation-to-user.html
Thanks for your enquiry, we'll contact you on the following email address: [[contact-email]]
Feel free to contact us any time through our website at [[webAddress]]


// Transformed output sent to the user
Thanks for your enquiry, we'll contact you on the following email address: user@domain.com
Feel free to contact us any time through our website at http://mrare.co

Any other text in the template is output as normal. The template should contain valid HTML compatible with an email reader app.

The text version of the confirmation email will contain a basic copy of the HTML version with all HTML <tags> stripped.

Handling Multiple Forms

In some instances you may have a need for two forms on the same site to submit to two separate addresses using different templates.

This is simply a matter of creating two different versions of smtp.php to handle the different cases.

  • Copy the original smtp.php file and rename it eg. smtp-contact-2.php
  • Point the new form's action attribute to the new file: action="forms/smtp-contact-2.php"
  • Edit the details of smtp-contact-2.php to meet your needs for the second form.

Troubleshooting

Common errors that may arise during configuration of form handlers:

Common Errors
Error Description
Connection refused Could be caused by the SMTP server rejecting the connection from your web server or your web server may be behind a firewall and cannot reach the outside network. Contact your hosting provider to ascertain if this is the case.
Internal Server Error This is a very general error and can be hard to diagnose. Generally this is a syntax error in your smtp.php file. You can copy your code to an online PHP code checker to help identify problems in the syntax, or uncomment the first two lines of smtp.php to reveal more descriptive PHP error messages. Alternatively, check the error logs on your server for detailed information.
200 JSON Parse error, unexpected '<' The server is not returning JSON, instead it is producing error text in HTML format, so jQuery can't handle it as JSON. Check the network tab in your browser developer tools, locate the smtp.php request and view the response to read the full error text.
There was an error verifying the Google reCaptcha Check that your secret key is properly set in smtp.php.