How to Create a Contact Form with PHP and Send an Email
Create the form
First, before we create the form you need to grab your credentials from your Mailtrap account: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.';
}
?>