PHP Email Contact Form - Mailtrap 07069564369
PHP Email Contact Form - Mailtrap 07069564369
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.
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
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.
Skip to Navigation
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>
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>
https://mailtrap.io/blog/php-email-contact-form/ 2/23
9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap
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 }
}
};
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:
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>";
}
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
https://mailtrap.io/blog/php-email-contact-form/ 4/23
9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap
Skip to Navigation
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);
header('Location: thank-you.html');
} else {
$errorMessage = 'Oops, something went wrong. Please try again l
}
} else {
<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 formValues = {
name: form.elements.name.value,
email: form.elements.email.value,
message: form.elements.message.value
};
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
$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';
if($mail->send()){
header('Location: thank-you.html'); // Redirect to 'thank you'
} else {
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}
}
};
};
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.
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
<?php
?>
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):
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]>');
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).
if($uploadStatus == 1){
Skip to Navigation
https://mailtrap.io/blog/php-email-contact-form/ 12/23
9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap
// Boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// 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,
The code for email contact form with attachment in PHPMailer would look much simpler
though:
Skip to Navigation
https://mailtrap.io/blog/php-email-contact-form/ 13/23
9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap
<?php
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->AddAttachment($_FILES["attachment"]["tmp_name"], $_FILES["attachm
if($mail->send()) {
$resultMessage = 'Message has been sent';
} else {
$resultMessage = 'Message could not be sent.';
}
?>
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.
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:
https://mailtrap.io/blog/php-email-contact-form/ 15/23
9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap
https://mailtrap.io/blog/php-email-contact-form/ 16/23
9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap
<?php
$errors = [];
$errorMessage = '';
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'
?>
<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>
<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}
}
};
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
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);
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.
https://mailtrap.io/blog/php-email-contact-form/ 19/23
9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap
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.
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.
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);
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;
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.
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
phptechie
This is an excellent post. This is really helpful for my business websites. It saved a
lot of time.
kambale
is my first time me sending these on the bottom on these for say. It looks as though
you’ve already say that!
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.
In 3 Clicks
Sign Up Now
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
https://mailtrap.io/blog/php-email-contact-form/ 22/23
9/7/23, 1:30 AM PHP Email Contact Form | Mailtrap
Coupler.io
https://mailtrap.io/blog/php-email-contact-form/ 23/23