Site icon Mailtrap

PHP Email Contact Form

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:

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.

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:

<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="myEmail" type="text" /></p>
<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:

<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="email" type="text" /></p>
<p><label>Message:</label>  <textarea name="message"></textarea> </p>

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

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.min.js"></script>
<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>

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

<?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.

<!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 = 'example@example.com';
       $emailSubject = 'New email from your contact form';
       $headers = ['From' => $email, 'Reply-To' => $email, 'Content-type' => 'text/html; charset=utf-8'];
       $bodyParagraphs = ["Name: {$name}", "Email: {$email}", "Message:", $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 later';
       }

   } else {

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

?>
<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 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.min.js"></script>
 <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>

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:

<?php
use PHPMailer\PHPMailer\PHPMailer;
require_once __DIR__ . '/vendor/autoload.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)) {
       $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('example@example.com', 'Me');
       $mail->Subject = 'New message from your website';

       // Enable HTML if needed
       $mail->isHTML(true);
       $bodyParagraphs = ["Name: {$name}", "Email: {$email}", "Message:", nl2br($message)];
       $body = join('<br />', $bodyParagraphs);
       $mail->Body = $body;
       echo $body;

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

           $errorMessage = 'Oops, something went wrong. Mailer Error: ' . $mail->ErrorInfo;
       }

   }

}

?>

<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.min.js"></script>

 <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>

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 <brian@example.com>, Mary <mary@example.com>';
@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 address
$arrEmail = array('Mary <mary@example.com>', 'Kelly <kelly@example.com>');

foreach($arrEmail as $key => $email_to)
    @mail($email_to, $email_subject, $email_message, $headers);

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">
</div>

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"], $targetFilePath)){ 
                    $uploadedFile = $targetFilePath; 
                }else{ 
                    $uploadStatus = 0; 
                    $statusMsg = "Sorry, there was an error uploading your file."; 
                } 
            }else{ 
                $uploadStatus = 0; 
                $statusMsg = 'Sorry, only '.implode('/', $allowFileTypes).' files are allowed to upload.'; 
            } 
        } 
         
        if($uploadStatus == 1){

Fourth, do the rest:

// 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: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";  
                 
                // Multipart boundary  
                $message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" . 
                "Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\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; name=\"".basename($uploadedFile)."\"\n" .  
                    "Content-Description: ".basename($uploadedFile)."\n" . 
                    "Content-Disposition: attachment;\n" . " filename=\"".basename($uploadedFile)."\"; size=".filesize($uploadedFile).";\n" .  
                    "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n"; 
                }
$message .= "--{$mime_boundary}--"; 
                $returnpath = "-f" . $email; 
                 
                // Send email 
                $mail = mail($toEmail, $emailSubject, $message, $headers, $returnpath); 
                 
                // Delete attachment file from the server 
                @unlink($uploadedFile); 
            }else{

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

<?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('address.from@example.com', 'Address from');
  $mail->addAddress('address.to@example.com', 'Address to');
  $mail->Subject = 'Email with attachment';
  $mail->isHTML(true);
  $mail->Body = '<h1>Hi there </h1>';

  $mail->AddAttachment($_FILES["attachment"]["tmp_name"], $_FILES["attachment"]["name"]);

 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.

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

<?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?secret={$secret}&response={$recaptchaResponse}";
    $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 = 'example@example.com';
        $emailSubject = 'New email from your contact form';
        $headers = ['From' => $email, 'Reply-To' => $email, 'Content-type' => 'text/html; charset=utf-8'];

        $bodyParagraphs = ["Name: {$name}", "Email: {$email}", "Message:", $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 wrong. Please try again later</p>";
        }
    }
}

?>

<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 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>
      <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/validate.min.js"></script>
  <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>

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' => $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.

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":"mailtrap@mailtrap.club","name":"Mailtrap Test"},"to":[{"email":"viktoriia.ivanenko@railsware.com"}],"subject":"You are awesome!","text":"Congrats for sending test email with Mailtrap!","category":"Integration Test"}',
    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

<?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.

Exit mobile version