How to Create a Contact Form with PHP and Send an Email

2 years ago admin PHP

In this tutorial, we will see how to create a contact form with PHP and send an email locally, we will use Mailtrap as an email delivery service, and PHPMailer library to send emails.


Create the form

First, before we create the form you need to grab your credentials from your Mailtrap account:

Grab the code
Next we create the form.

                                                    
                                                                                                                
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <title>PHP Contact Form</title>
  </head>
  <body class="bg-light">
    <div class="container">
        <div class="row my-5">
            <div class="col-md-6 mx-auto">
                <div class="card">
                    <div class="card-header bg-white text-center">
                        <h3 class="mt-2">Contact Us</h3>
                    </div>
                    <div class="card-body">
                        <form action="send_email.php" method="post">
                            <div class="mb-3">
                                <input type="text" name="name" class="form-control" placeholder="Your Name" required>
                            </div>
                            <div class="mb-3">
                                <input type="email" name="email" class="form-control" placeholder="Your Email" required>
                            </div>
                            <div class="mb-3">
                                <textarea name="message" class="form-control" placeholder="Message" required></textarea>
                            </div>
                            <div class="mb-3">
                                <button class="btn btn-primary" type="submit">
                                    Send
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
  </body>
</html>

Create the send_email.php file

Next, to send the email download the PHPMailer library and extract the contents and copy the "PHPMailer" folder into your project directory, next we will use the credentials you did grab from your Mailtrap account to send and receive emails.

                                                        
                                                                                                                        
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require './PHPMailer/src/Exception.php';
require './PHPMailer/src/PHPMailer.php';
require './PHPMailer/src/SMTP.php';


if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['message'])) {
    $name = htmlspecialchars($_POST['name']);
    $email = htmlspecialchars($_POST['email']);
    $message = htmlspecialchars($_POST['message']);

    try {
        $mail = new PHPMailer();
        $mail->isSMTP();
        $mail->Host = 'sandbox.smtp.mailtrap.io';
        $mail->SMTPAuth = true;
        $mail->Port = 2525;
        $mail->Username = 'YOUR USERNAME';
        $mail->Password = 'YOUR PASSWORD';

        $mail->setFrom($email, $name);
        $mail->addAddress($email); // Replace with the recipient's email address
        $mail->Subject = 'New message';
        $mail->Body = $message;

        // Send the email
        $mail->send();

        echo 'Message sent successfully!';

    } catch (Exception $e) {
        echo 'Message could not be sent. Error: ', $mail->ErrorInfo;
    }
} else {
    echo 'Invalid request.';
}
?>

Related Tuorials

How to Handle Forms with PHP (GET and POST Methods Explained)

When building dynamic websites using PHP, you need to get and process the user input data. Here come...


How to Create and Use Functions in PHP (With Examples for Beginners)

In PHP, a function is a block of code that is executed to perform a specific task. This is a go...


How to Use Variables and Data Types in PHP (A Clear Guide for Absolute Beginners) Part 2

In the second part of this guide, we will see more PHP types.Also, we will see how to check a variab...


How to Use Variables and Data Types in PHP (A Clear Guide for Absolute Beginners) Part 1

The first thing you need to understand when learning PHP is variables and data types. In this g...


How to Install and Run PHP on Your Localhost (Step-by-Step Guide)

If you want to learn PHP or build a web application with it, the first step is to create a working l...


CRUD Application with PHP PDO Ajax, and MySQL Part 2

In the second part of this tutorial, we will get all the students from the database and display them...


CRUD Application with PHP PDO Ajax, and MySQL Part 1

In this tutorial we will see how to create a crud application with PHP PDO Ajax, and MySQL, the user...


How to Sort Associative Arrays in Descending Order According to the Key Value in PHP

in this lesson, we will see how to sort associative arrays in descending order according to the key...


How to Sort Associative Arrays in Ascending Order According to the Key Value in PHP

in this lesson, we will see how to sort associative arrays in ascending order according to the key v...


How to Sort Associative Arrays in Descending Order According to the Value in PHP

in this lesson, we will see how to sort associative arrays in descending order according to the valu...