0% found this document useful (0 votes)
31 views

PHP Email Contact Form - Mailtrap 07069564369

This document provides instructions for building a PHP email contact form in 3 steps: 1) Build a basic HTML contact form with input fields. 2) Add POST method and action attributes to submit the form data to a PHP file. 3) Add data validation on both the client-side and server-side to validate the form entries and protect against spam. Additional features like reCAPTCHA and form handling errors are also discussed.

Uploaded by

All In One
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

PHP Email Contact Form - Mailtrap 07069564369

This document provides instructions for building a PHP email contact form in 3 steps: 1) Build a basic HTML contact form with input fields. 2) Add POST method and action attributes to submit the form data to a PHP file. 3) Add data validation on both the client-side and server-side to validate the form entries and protect against spam. Additional features like reCAPTCHA and form handling errors are also discussed.

Uploaded by

All In One
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap

PHP Email Contact Form


On October 07, 2022 14min read

Piotr Malek
Technical Content Writer @ Mailtrap

Contact forms have always been a pretty effective alternative to mailto links spread
around webpages. And that’s still the case in 2022. 

They’re easy to use for customers and harder to figure out for email harvesters. As you
would expect, building an effective PHP email contact form isn’t hard at all. We’re going
to explain the process step by step in this article.

What we’ll basically do is this:

Build a simple HTML contact form with input fields (and optional CSS) and embed it
on our website

Write a PHP script that will effectively handle sending email messages

Save the inserted details into a spreadsheet

Send an autoresponder to a user, letting them know we’ll handle their request

Provide an overview of some common issues with PHP email form sending

We’ll not only explain how to make a php email form, but we’ll also show you how to
secure the mail form with reCaptcha and how to perform form validation, as well as how
to handle common errors. So, let’s begin.

PHP Contact Form - Tutorial by Mailtrap

Skip to Navigation

Building a simple PHP contact form tutorial


For starters, we’ll need to build a simple form with just HTML code. If you don’t care
much about the visual side of it, it can be as simple as this:

Mailtrap uses cookies to enhance your browsing experience, analyze traffic


and serve targeted ads. By continuing to use our site and application, you Accept
agree to our Privacy policy and use of cookies.

https://mailtrap.io/blog/php-email-contact-form/ 1/23
9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap

<form>
<h2>Contact us</h2>
<p><label>First Name:</label> <input name="myEmail" type="text" /></p>
<p><label>Email Address:</label> <input style="cursor: pointer;" name="myE
<p><label>Message:</label> <textarea name="message"></textarea> </p>
<p><input type="submit" value="Send" /></p>
</form>

Of course, without any CSS it looks really ugly:

But it will be just fine for demonstration purposes. If you’re not into writing CSS at the
moment, you can use any of the hundreds of available email form builders and templates
with a beautiful design for the input fields of the form data, catchy submit buttons, and
an overall appealing UX design. 

Some options include Simfatic, 123FormBuilder, and PHP Jabbers. CodeCanyon has
hundreds of tools with reviews for each to make the choice easier.  

Okay, we’ve got the contact form, but whatever data users insert goes straight into a
black hole. So, we’ll need to add two more elements to the form–ACTION, and METHOD.

In our case, we’ll want to load a new PHP page in the background that we’ll talk about in
the next chapter. Since we’ll be processing the data, we’re legally obliged to protect the
user’s details (name and email address), making the POST method a safer option. Using
GET would mean these details get included in the URL of the following page, something
we’d rather avoid. Keep in mind that URL has its limits (trailing slash value must not
exceed 2,048 characters), therefore GET method can’t really be used for contact forms
because of the URL limitations.

All we need to do now is include these two attributes in the code we previously used:

Skip to Navigation
<form method="POST" action="form.php" id="contact-form">
<h2>Contact us</h2>
<p><label>First Name:</label> <input name="name" type="text" /></p>
<p><label>Email Address:</label> <input style="cursor: pointer;" name="ema
<p><label>Message:</label> <textarea name="message"></textarea> </p>

<p><input type="submit" value="Send" /></p>


</form>

Mailtrap uses cookies to enhance your browsing experience, analyze traffic


and serve targeted ads. By continuing to use our site and application, you
agree to our Privacy policy and use of cookies.

https://mailtrap.io/blog/php-email-contact-form/ 2/23
9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap

Data Validation and Verification


To get rid of some spammers, but also to protect your users from accidentally mistyping
their contact details, it’s worth adding some validation algorithms to the contact form.
For the highest chance of success, consider doing this on both the client- and server-
side. 

Client-side validation will quickly return any errors on the frontend, letting a user fix them
right away. Server-side verification will also catch those that passed the initial test (by,
for example, disabling JavaScript in the browser) but shouldn’t have.

While you can write your own script, it’s often worth using what’s already been built and
tested. We will use a bulletproof solution for schema validation – https://validatejs.org/.
For simplicity, just add a library from a CDN.

<script src="//cdnjs.cloudflare.com/ajax/libs/validate.js/0.13.1/validate.

<script>
const constraints = {
name: {
presence: { allowEmpty: false }
},
email: {
presence: { allowEmpty: false },
email: true
},
message: {
presence: { allowEmpty: false }
}
};

const form = document.getElementById('contact-form');

form.addEventListener('submit', function (event) {


const formValues = {
name: form.elements.name.value,
email: form.elements.email.value,
message: form.elements.message.value
};

const errors = validate(formValues, constraints);

if (errors) {
event.preventDefault();
const errorMessage = Object
.values(errors)
.map(function (fieldValues) { return fieldValues.join(', ')})
.join("\n");

alert(errorMessage);
Skip to Navigation }
}, false);
</script>

For the server-side validation, you can use the following code:

Mailtrap uses cookies to enhance your browsing experience, analyze traffic


and serve targeted ads. By continuing to use our site and application, you
agree to our Privacy policy and use of cookies.

https://mailtrap.io/blog/php-email-contact-form/ 3/23
9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap

<?php

$errors = [];

if (!empty($_POST)) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

if (empty($name)) {
$errors[] = 'Name is empty';
}

if (empty($email)) {
$errors[] = 'Email is empty';
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Email is invalid';
}

if (empty($message)) {
$errors[] = 'Message is empty';
}
}

If either verification fails, it would be a good idea to let the user know. You can use the
following code to build an error message:

<?php
if (!empty($errors)) {
$allErrors = join('<br/>', $errors);
$errorMessage = "<p style='color: red;'>{$allErrors}</p>";
}

You are free to render this message anywhere on your page. 

PHP code to send email from a contact


form
Our form is leading somewhere, but it’s not clear where. Let’s add some action points and
use the default mail() function to send a simple email after submission.

The code of this PHP contact form specifies the headers and body of a message and
sends each email with the mail() method. It also includes the validations we explained in
the previous chapter and the HTML form itself.

Skip to Navigation

Mailtrap uses cookies to enhance your browsing experience, analyze traffic


and serve targeted ads. By continuing to use our site and application, you
agree to our Privacy policy and use of cookies.

https://mailtrap.io/blog/php-email-contact-form/ 4/23
9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap

Skip to Navigation

Mailtrap uses cookies to enhance your browsing experience, analyze traffic


and serve targeted ads. By continuing to use our site and application, you
agree to our Privacy policy and use of cookies.

https://mailtrap.io/blog/php-email-contact-form/ 5/23
9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap

<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Contact form submission</title>
</head>
<body>

<?php

$errors = [];
$errorMessage = '';

if (!empty($_POST)) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

if (empty($name)) {
$errors[] = 'Name is empty';
}

if (empty($email)) {
$errors[] = 'Email is empty';
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Email is invalid';
}

if (empty($message)) {
$errors[] = 'Message is empty';
}

if (empty($errors)) {
$toEmail = '[email protected]';
$emailSubject = 'New email from your contact form';
$headers = ['From' => $email, 'Reply-To' => $email, 'Content-type'
$bodyParagraphs = ["Name: {$name}", "Email: {$email}", "Message:",
$body = join(PHP_EOL, $bodyParagraphs);

if (mail($toEmail, $emailSubject, $body, $headers)) {

header('Location: thank-you.html');
} else {
$errorMessage = 'Oops, something went wrong. Please try again l
}

} else {

$allErrors = join('<br/>', $errors);


$errorMessage = "<p style='color: red;'>{$allErrors}</p>";
}
}

Skip to Navigation ?>


<html>
<body>
<form method="post" id="contact-form">
<h2>Contact us</h2>
<?php echo((!empty($errorMessage)) ? $errorMessage : '') ?>
<p>
<label>First Name:</label>
<input name="name" type="text"/>
</p>
<p>
<label>Email
Mailtrap uses cookies to enhance Address:</label>
your browsing experience, analyze traffic
<input style="cursor:
and serve targeted ads. By continuing to use our site and pointer;" name="email" type="text"/>
application, you
agree to our Privacy policy and
</p> use of cookies.
<p>
https://mailtrap.io/blog/php-email-contact-form/ 6/23
9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap
<p>
<label>Message:</label>
<textarea name="message"></textarea>
</p>
<p>

<input type="submit" value="Send"/>


</p>
</form>

<script src="//cdnjs.cloudflare.com/ajax/libs/validate.js/0.13.1/validate
<script>

const constraints = {
name: {
presence: { allowEmpty: false }
},
email: {
presence: { allowEmpty: false },
email: true
},
message: {
presence: { allowEmpty: false }
}
};

const form = document.getElementById('contact-form');


form.addEventListener('submit', function (event) {

const formValues = {
name: form.elements.name.value,
email: form.elements.email.value,
message: form.elements.message.value
};

const errors = validate(formValues, constraints);


if (errors) {
event.preventDefault();
const errorMessage = Object
.values(errors)
.map(function (fieldValues) {
return fieldValues.join(', ')
})
.join("\n");

alert(errorMessage);
}
}, false);
</script>
</body>
</html>

Skip to Navigation

If the PHP contact form returns error 500, double check to see if you specified the
parameters of the mail() function properly. Make sure the mail server is properly
configured on your machine.

PHP contact forms, of course, allow for different methods of sending emails. Arguably
the most popular choice for sending emails in PHP is PHPMailer. If you’re not familiar with
it, read our tutorial on how to send emails using PHPMailer.

Here’s how PHPMailer code would look like for this page:
Mailtrap uses cookies to enhance your browsing experience, analyze traffic
and serve targeted ads. By continuing to use our site and application, you
agree to our Privacy policy and use of cookies.

https://mailtrap.io/blog/php-email-contact-form/ 7/23
9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap

Skip to Navigation

Table of Contents

Building a simple PHP


contact form tutorial
Data Validation and
Verification
Mailtrap uses cookies to enhance your browsing experience, analyze traffic
PHP code to send email and serve targeted ads. By continuing to use our site and application, you
from a contact form agree to our Privacy policy and use of cookies.
How to add the
https://mailtrap.io/blog/php-email-contact-form/ 8/23
9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap
How to add the
“Accept terms/privacy <?php
policy” checkbox to use PHPMailer\PHPMailer\PHPMailer;
your form?
require_once __DIR__ . '/vendor/autoload.php';
How to send the mail $errors = [];
form to multiple
$errorMessage = '';
recipients?

How to send emails


if (!empty($_POST)) {
with attachments
using the PHP contact $name = $_POST['name'];
form? $email = $_POST['email'];
PHP contact form with $message = $_POST['message'];
Google reCaptcha

Storing responses in if (empty($name)) {


Google Spreadsheets $errors[] = 'Name is empty';
PHP contact form }
doesn’t send emails: how
to fix the issue?
if (empty($email)) {
Code should match
$errors[] = 'Email is empty';
the form method
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
Configure the
$errors[] = 'Email is invalid';
localhost mail server
properly
}
Use a different mailing
package

Enable PHP’s custom


mail.log if (empty($message)) {
Use API/SMTP with a
$errors[] = 'Message is empty';
reputable mail service }
provider
Wrapping up if (!empty($errors)) {
$allErrors = join('<br/>', $errors);
$errorMessage = "<p style='color: red;'>{$allErrors}</p>";
} else {
$mail = new PHPMailer();

// specify SMTP credentials

$mail->isSMTP();
$mail->Host = 'smtp.mailtrap.io';
$mail->SMTPAuth = true;
$mail->Username = 'your_smtp_username';
$mail->Password = 'your_smtp_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 2525;
$mail->setFrom($email, 'Mailtrap Website');
$mail->addAddress('[email protected]', 'Me');
$mail->Subject = 'New message from your website';

// Enable HTML if needed


$mail->isHTML(true);
$bodyParagraphs = ["Name: {$name}", "Email: {$email}", "Message:",
$body = join('<br />', $bodyParagraphs);
$mail->Body = $body;
Skip to Navigation echo $body;

if($mail->send()){
header('Location: thank-you.html'); // Redirect to 'thank you'
} else {

$errorMessage = 'Oops, something went wrong. Mailer Error: ' .


}

Mailtrap uses cookies}to enhance your browsing experience, analyze traffic


and serve targeted ads. By continuing to use our site and application, you
agree to our Privacy policy
?> and use of cookies.

https://mailtrap.io/blog/php-email-contact-form/ 9/23
9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap

<html>
<body>
<form action="/swiftmailer_form.php" method="post" id="contact-form">
<h2>Contact us</h2>
<?php echo((!empty($errorMessage)) ? $errorMessage : '') ?>
<p>
<label>First Name:</label>
<input name="name" type="text"/>
</p>
<p>
<label>Email Address:</label>
<input style="cursor: pointer;" name="email" type="text"/>
</p>
<p>
<label>Message:</label>
<textarea name="message"></textarea>
</p>
<p>
<input type="submit" value="Send"/>
</p>
</form>

<script src="//cdnjs.cloudflare.com/ajax/libs/validate.js/0.13.1/validate

<script>

const constraints = {
name: {
presence: {allowEmpty: false}
},
email: {
presence: {allowEmpty: false},
email: true
},
message: {
presence: {allowEmpty: false}
}
};

const form = document.getElementById('contact-form');


form.addEventListener('submit', function (event) {
const formValues = {
name: form.elements.name.value,
email: form.elements.email.value,
message: form.elements.message.value

};

const errors = validate(formValues, constraints);

if (errors) {
event.preventDefault();
Skip to Navigation
const errorMessage = Object
.values(errors)
.map(function (fieldValues) {
return fieldValues.join(', ')
})
.join("\n");
alert(errorMessage);

}, false);
Mailtrap uses cookies to enhance your browsing experience, analyze traffic
and serve targeted ads. By continuing to use our site and application, you
</script>
agree to our Privacy policy and use of cookies.
</body>
https://mailtrap.io/blog/php-email-contact-form/ 10/23
9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap

</html>

There are several other reliable tools that can handle the task as well. Check out our
guide to sending emails in PHP for more details.

How to add the “Accept terms/privacy policy” checkbox to your


form?

This one falls under the category of a simple form with a single check box.

Here is how the code for a simple mail form with a checkbox in PHP would look like:
The form itself

<form action="checkbox-form.php" method="post">


Do you accept terms and conditions?
<input type="checkbox" name="formTerms" value="Yes" />
<input type="submit" name="formSubmit" value="Submit" />
</form>

And the PHP script for it

<?php

if (isset($_POST['formTerms']) && $_POST['formTerms'] == 'Yes') {


echo "Terms accepted.";
} else {
echo "Terms not accepted.";
}

?>

How to send the mail form to multiple recipients?

With PHP email forms, the rule is no different from PHP email sending in general. Add
multiple receiving email addresses for the submitted forms via cc and bcc methods (that
is using a comma):

$email_to = 'Brian <[email protected]>, Mary <[email protected]>';


@mail($email_to, $email_subject, $email_message, $headers);

Or use a foreach:

//list of emails in array format and each one will see their own to email
$arrEmail = array('Mary <[email protected]>', 'Kelly <[email protected]>');

foreach($arrEmail as $key => $email_to)


@mail($email_to, $email_subject, $email_message, $headers);

Skip to Navigation
How to send emails with attachments using the PHP contact form?

If your contact form has a file upload field, the file needs to be sent with an email as an
attachment. With the mail() function, you can easily send an email contact form with an
attachment in PHP. Just add the following pieces of code to your app.

First, you need to add an attachment field to your HTML mail form. Add the following
lines of code within the <form> tags: 

<div>
<input type="file" name="attachment">
Mailtrap uses cookies</div>
to enhance your browsing experience, analyze traffic
and serve targeted ads. By continuing to use our site and application, you
agree to our Privacy policy and use of cookies.

https://mailtrap.io/blog/php-email-contact-form/ 11/23
9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap

Second, check and validate the file extension to allow certain file formats (PDF, PNG,
and/or MS Word files).

// File upload settings


$attachmentUploadDir = "uploads/";
$allowFileTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg');

Third, upload the attachment file:

// Upload attachment file


if(!empty($_FILES["attachment"]["name"])){

// File path config


$targetDir = $attachmentUploadDir;
$fileName = basename($_FILES["attachment"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);

// Allow certain file formats


if(in_array($fileType, $allowFileTypes)){
// Upload file to the server
if(move_uploaded_file($_FILES["attachment"]["tmp_name"], $
$uploadedFile = $targetFilePath;
}else{
$uploadStatus = 0;
$statusMsg = "Sorry, there was an error uploading your
}
}else{
$uploadStatus = 0;
$statusMsg = 'Sorry, only '.implode('/', $allowFileTypes).
}
}

if($uploadStatus == 1){

Fourth, do the rest:

Skip to Navigation

Mailtrap uses cookies to enhance your browsing experience, analyze traffic


and serve targeted ads. By continuing to use our site and application, you
agree to our Privacy policy and use of cookies.

https://mailtrap.io/blog/php-email-contact-form/ 12/23
9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap

// Add attachment to email


if(!empty($uploadedFile) && file_exists($uploadedFile)){

// Boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

// Headers for attachment


$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multi

// Multipart boundary
$message = "--{$mime_boundary}\n" . "Content-Type: text/ht
"Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n

// Preparing attachment
if(is_file($uploadedFile)){
$message .= "--{$mime_boundary}\n";
$fp = @fopen($uploadedFile,"rb");
$data = @fread($fp,filesize($uploadedFile));
@fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; n
"Content-Description: ".basename($uploadedFile)."\n" .
"Content-Disposition: attachment;\n" . " filename=\"".
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\
}
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $email;

// Send email
$mail = mail($toEmail, $emailSubject, $message, $headers,

// Delete attachment file from the server


@unlink($uploadedFile);
}else{

The code for email contact form with attachment in PHPMailer would look much simpler
though:

Skip to Navigation

Mailtrap uses cookies to enhance your browsing experience, analyze traffic


and serve targeted ads. By continuing to use our site and application, you
agree to our Privacy policy and use of cookies.

https://mailtrap.io/blog/php-email-contact-form/ 13/23
9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap

<?php

// Start with PHPMailer class


use PHPMailer\PHPMailer\PHPMailer;

require_once './vendor/autoload.php';

$resultMessage = '';

if (!empty($_FILES["attachment"])) {
// create a new object
$mail = new PHPMailer();

// configure an SMTP
$mail->isSMTP();
$mail->SMTPSecure = 'tls';
$mail->Host = 'smtp.mailtrap.io';
$mail->SMTPAuth = true;
$mail->Port = 2525;
$mail->Username = 'your-username';
$mail->Password = 'your-password';

$mail->setFrom('[email protected]', 'Address from');


$mail->addAddress('[email protected]', 'Address to');
$mail->Subject = 'Email with attachment';
$mail->isHTML(true);
$mail->Body = '<h1>Hi there </h1>';

$mail->AddAttachment($_FILES["attachment"]["tmp_name"], $_FILES["attachm

if($mail->send()) {
$resultMessage = 'Message has been sent';
} else {
$resultMessage = 'Message could not be sent.';
}

?>

And that’s about it.

By all means, use mail() for testing, or if getting a contact form response every now and
then is all you need from mailing functionality. But if you’re going to send lots of
transactional emails, it’s worth looking for a more reliable alternative. Find out more
about how to test emails sent from PHP.

PHP contact form with Google reCaptcha


To add one more layer of security, you may want to add a simple reCaptcha script to
your PHP mail form. You can do this in a very simple way. 

First of all, head to https://www.google.com/recaptcha/admin/create and fill out the form


you’ll find there. You can choose between reCaptcha v2 and v3 (v1 is no longer
supported). To make it simple, we’ll opt for the former. 

ReCaptcha v2 is sent with a form, and we can easily handle it in the backend with the
rest of the form fields. ReCaptcha v3, on the other hand, needs to be called manually on
the frontend. This is doable but would require us to rewrite the entire code. Let’s leave
this for another occasion.
Mailtrap uses cookies to enhance your browsing experience, analyze traffic
and serve targeted ads. By continuing to use our site and application, you
agree to our Privacy policy and use of cookies.

https://mailtrap.io/blog/php-email-contact-form/ 14/23
9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap

Submit the form and you’ll see your individual Site Key and Secret Key. Check out the
whole form with the added ReCaptcha:

Mailtrap uses cookies to enhance your browsing experience, analyze traffic


and serve targeted ads. By continuing to use our site and application, you
agree to our Privacy policy and use of cookies.

https://mailtrap.io/blog/php-email-contact-form/ 15/23
9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap

Mailtrap uses cookies to enhance your browsing experience, analyze traffic


and serve targeted ads. By continuing to use our site and application, you
agree to our Privacy policy and use of cookies.

https://mailtrap.io/blog/php-email-contact-form/ 16/23
9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap

<?php

$errors = [];
$errorMessage = '';

$secret = 'your secret key';

if (!empty($_POST)) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$recaptchaResponse = $_POST['g-recaptcha-response'];

$recaptchaUrl = "https://www.google.com/recaptcha/api/siteverify?secre
$verify = json_decode(file_get_contents($recaptchaUrl));

if (!$verify->success) {
$errors[] = 'Recaptcha failed';
}

if (empty($name)) {
$errors[] = 'Name is empty';
}

if (empty($email)) {
$errors[] = 'Email is empty';
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Email is invalid';
}

if (empty($message)) {
$errors[] = 'Message is empty';
}

if (!empty($errors)) {
$allErrors = join('<br/>', $errors);
$errorMessage = "<p style='color: red;'>{$allErrors}</p>";
} else {
$toEmail = '[email protected]';
$emailSubject = 'New email from your contact form';
$headers = ['From' => $email, 'Reply-To' => $email, 'Content-type'

$bodyParagraphs = ["Name: {$name}", "Email: {$email}", "Message:",


$body = join(PHP_EOL, $bodyParagraphs);

if (mail($toEmail, $emailSubject, $body, $headers)) {


header('Location: thank-you.html');
} else {
$errorMessage = "<p style='color: red;'>Oops, something went w
}
}
}

?>

<html>
<body>
<script src="https://www.google.com/recaptcha/api.js"></script>
<form action="/form.php" method="post" id="contact-form">
<h2>Contact us</h2>

<?php echo((!empty($errorMessage)) ? $errorMessage : '') ?>


<p>
<label>First
Mailtrap uses cookies to enhance Name:</label>
your browsing experience, analyze traffic
<input name="name"
and serve targeted ads. By continuing type="text"/>
to use our site and application, you
agree to our Privacy policy</p>
and use of cookies.
<p>
https://mailtrap.io/blog/php-email-contact-form/ 17/23
9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap
<p>
<label>Email Address:</label>
<input style="cursor: pointer;" name="email" type="text"/>
</p>
<p>
<label>Message:</label>
<textarea name="message"></textarea>
</p>

<p>
<button
class="g-recaptcha"
type="submit"
data-sitekey="your site key"
data-callback='onRecaptchaSuccess'
>
Submit
</button>
</p>
</form>
<script src="//cdnjs.cloudflare.com/ajax/libs/validate.js/0.13.1/validat
<script>
const constraints = {
name: {
presence: {allowEmpty: false}
},
email: {
presence: {allowEmpty: false},
email: true
},
message: {
presence: {allowEmpty: false}
}
};

const form = document.getElementById('contact-form');

form.addEventListener('submit', function (event) {


const formValues = {
name: form.elements.name.value,
email: form.elements.email.value,
message: form.elements.message.value
};

const errors = validate(formValues, constraints);

if (errors) {
event.preventDefault();
const errorMessage = Object
.values(errors)
.map(function (fieldValues) {
return fieldValues.join(', ')
})
.join("\n");

alert(errorMessage);
}
}, false);

function onRecaptchaSuccess () {
document.getElementById('contact-form').submit()
}
</script>
</body>
</html>
Mailtrap uses cookies to enhance your browsing experience, analyze traffic
and serve targeted ads. By continuing to use our site and application, you
agree to our Privacy policy and use of cookies.

https://mailtrap.io/blog/php-email-contact-form/ 18/23
9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap

Storing responses in Google Spreadsheets

Since we only want to save a few values somewhere, we can just populate a Google
Sheet with the results. Let’s connect Zapier’s webhooks with a spreadsheet. For a start,
don’t forget to specify table columns, which the app will use to recognize where to put
data sent by our form. 

Create a new Zap that will connect the webhook and spreadsheets, following the
instructions in Zapier. They are super clear, so you will be able to figure it out on your
own. In the app, your Zap will look like this.

Use this code to send a request to Zapier and see how your spreadsheet is populating
after each form submission.

$zapierWebhookUrl = '<your-webhook-url>';
$ch = curl_init($zapierWebhookUrl);
$payload = json_encode(['email' => $email, 'name' => $name, 'message' => $
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_exec($ch);
curl_close($ch);

PHP contact form doesn’t send emails:


how to fix the issue?
Contact forms in PHP either use mail() function or SMTP authentication to send emails.
This means some common issues you may come across are connected to either
malfunctioning of the mail() function, or to the incorrect settings of the SMTP.  There is a
bare minimum checklist of what you can do to troubleshoot:

Code should match the form method

When you set the form method to POST, then make sure you use $_POST to look for
your form values. Otherwise, if you set it to GET or didn’t set it at all, then you need to
use $_GET to look for your form values.

Mailtrap uses cookies to enhance your browsing experience, analyze traffic


and serve targeted ads. By continuing to use our site and application, you
agree to our Privacy policy and use of cookies.

https://mailtrap.io/blog/php-email-contact-form/ 19/23
9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap

Configure the localhost mail server properly

If your workstation is local and you develop locally using WAMP, MAMP, or XAMPP, an
email server might not be installed on your workstation. However, it is obligatory to install
since PHP cannot send mail by default.

Use a different mailing package

PHP’s built-in mail() function is simple but it has quite a few disadvantages. Consider the
alternatives that offer more flexibility and fewer errors like PHPMailer or Symfony Mailer.

Enable PHP’s custom mail.log

This would not record the complete SMTP interaction, but at least function call
parameters and invocation script.

ini_set("mail.log", "/tmp/mail.log");
ini_set("mail.add_x_header", TRUE);

Use API/SMTP with a reputable mail service provider 

The mail() function doesn’t support external SMTP servers, and this is a serious
bottleneck. As emails are sent from your own servers rather than those of ESPs (Email
Sending Providers), they will frequently go to spam. So, you might actually send email
forms, but they would not necessarily reach the inbox. And that’s a serious issue.

Consider using the Email API/SMTP that would do the sending job and spare you
unnecessary time and effort. With Mailtrap Email Sending, you can start sending all the
necessary PHP email forms you need in roughly 5 minutes, with minimum configurations,
and the best possible results. 

The simple code snippet for the Mailtrap API PHP integration:

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
CURLOPT_URL => 'https://send.api.mailtrap.io/api/send',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>'{"from":{"email":"[email protected]","name"
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer <your api token>,
'Content-Type: application/json'
),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

Try Sending Emails in PHP with Mailtrap for Free

Or in case you prefer SMTP

Mailtrap uses cookies to enhance your browsing experience, analyze traffic


and serve targeted ads. By continuing to use our site and application, you
agree to our Privacy policy and use of cookies.

https://mailtrap.io/blog/php-email-contact-form/ 20/23
9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap

<?php
// configure an SMTP
$mail->isSMTP();
$mail->Host = 'smtp.mailtrap.io';
$mail->SMTPAuth = true;
$mail->Username = 'api';
$mail->Password = '********2ff0';
$mail->SMTPSecure = 'tls';
$mail->Port = 528;

Basically, what you need to do is go to Mailtrap and copy and paste the credentials. And
you can then try it for free. It could be quite a game-changer for your development
process.

Try Mailtrap for Free

Wrapping up
Do you sometimes wonder if a contact form is the right approach to email obfuscation?
Maybe there are more reliable approaches to filtering out spammers and making life
easier for our users? We discuss various approaches to the problem in our article on
email obfuscation.

One last note. Building an effective PHP email contact form isn’t hard at all. And there are
many ways you can do this. And in this article, you definitely saw a couple. What is much
harder is reaching the recipients’ inboxes. Sometimes, the PHP mail() function might not
be enough. This is where you might need the help of a reputable mail service provider to
get emails sent and delivered the way you want.

Article by

Piotr Malek
Technical Content Writer @ Mailtrap

Comments
5 replies

09:06 AM - Jul 28, 2020

phptechie

This is an excellent post. This is really helpful for my business websites. It saved a
lot of time.

12:27 PM - Sep 30, 2020

kambale

how can i download this codes?

Mailtrap uses cookies to enhance your browsing experience, analyze traffic


09:58 PMto
and serve targeted ads. By continuing - Jan
use 6,
our2021
site and application, you
agree to our Privacy policy and use of cookies.
Pedro Cortes
https://mailtrap.io/blog/php-email-contact-form/ 21/23
9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap

is my first time me sending these on the bottom on these for say. It looks as though
you’ve already say that!

09:20 PM - Feb 2, 2021

Peter

I have tried it, the validation works well, and I’m redirected to my index.html page
(instead of a thnak-you page), I have put my own e-mail address as “toEmail” but I
did not receive any email.

View all comments

Comments are closed.

Create Your Free Account

In 3 Clicks
Sign Up Now

Email Testing How to switch Helpful Contact


resources
Fake SMTP Migration from Sendgrid email: [email protected]
Mailtrap Blog
HTML Checker Migration from Mailgun
Help center
Spam Checker Migration from Mailchimp 
Transactional
Product
Emails Careers –
QA Automation
Pricing Railsware
Migration from Amazon SES
Testing API hiring
Status

Changelog Mailtrap VS
Email Sending
Privacy Policy Mailtrap vs Sendgrid
Email API
Terms of Service Mailtrap vs Mailgun
SMTP service
Navigational Information Mailtrap vs Mailchimp Transactional
Sending API
DPA Emails

Mailtrap vs Amazon SES

Mailtrap uses cookies to enhance your browsing experience, analyze traffic


and serve targeted ads. By continuing to use our site and application, you
agree to our Privacy policy and use of cookies.

https://mailtrap.io/blog/php-email-contact-form/ 22/23
9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap

© Railsware Products Studio LLC Railsware Blog

Coupler.io

Smart Checklist for Jira

Mailtrap uses cookies to enhance your browsing experience, analyze traffic


and serve targeted ads. By continuing to use our site and application, you
agree to our Privacy policy and use of cookies.

https://mailtrap.io/blog/php-email-contact-form/ 23/23

You might also like