Sending emails through a PHP script is a common requirement for many web applications. PHPMailer is a powerful and popular library that simplifies the process of sending emails in PHP. In this tutorial, we will guide you through the process of setting up and using PHPMailer to send emails using your PHP script.
Prerequisites
Before you begin, ensure that you have the following:
- A working PHP environment.
- PHPMailer library files. You can download them from the official PHPMailer GitHub repository.
- Basic knowledge of HTML and PHP.
File Structure
|--Mail
|---PHPMailer
|---index.php
Setting Up PHPMailer
- Download PHPMailer library files and extract them into your project directory.
- Create a file index.php or any file of your choice
- Include PHPMailer library files in your PHP script
<?php // Include PHPMailer library files require 'PHPMailer/src/PHPMailer.php'; require 'PHPMailer/src/SMTP.php'; require 'PHPMailer/src/Exception.php'; // Create a new PHPMailer instance use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; use PHPMailer\PHPMailer\Exception; $mail = new PHPMailer(true); // Passing `true` enables exceptions // Rest of your code... ?>
Configure the SMTP settings:
$mail->SMTPDebug = false; // Enable verbose debug output $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = 'itachi.pw'; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = 'support@itachi.pw'; // SMTP username $mail->Password = 'Your Password'; // SMTP password $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption, `ssl` also accepted $mail->Port = 587; // TCP port to connect to
Customize the email content:
$name = $_POST["name"]; $email = $_POST["email"]; $message = $_POST["message"]; $mail->setFrom('support@itachi.pw', 'This is a test from Support'); $mail->addAddress($email, $name); $mail->Subject = 'Build a contact form with PHP'; $mail->Body = $message;
Handling Form Submission
Create variables to store form data and errors:
$success = ""; $error = ""; $name = $message = $email = ""; $errors = array('name' => '', 'email' => '', 'message' => '');
Check if the form is submitted:
if (isset($_POST["submit"])) { // Handle form data... }
Try sending the email:
try { // Sending email code... $mail->send(); $name = $message = $email = ""; $success = "Message sent successfully"; } catch (Exception $e) { echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"; }
HTML Form Integration
Integrate the HTML form with PHP:
<form action="index.php" method="post"> <!-- Form fields and submit button... --> </form>
Display success and error messages:
<div class="text-2xl font-medium title-font rounded text-green-400 text-center"><?php echo $success ?></div> <div class="text-2xl font-medium title-font rounded-full text-red-400 text-center"><?php echo $error ?></div>
Populate form fields with submitted data:
<input type="text" id="name" name="name" value="<?php echo htmlspecialchars($name) ?>" class="..."> <input type="email" id="email" name="email" value="<?php echo htmlspecialchars($email) ?>" class="..."> <textarea id="message" name="message" class="..."><?php echo htmlspecialchars($message) ?></textarea>
This is the Entire Code
<?php // Include PHPMailer library files require 'PHPMailer/src/PHPMailer.php'; require 'PHPMailer/src/SMTP.php'; require 'PHPMailer/src/Exception.php'; // Create a new PHPMailer instance use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; use PHPMailer\PHPMailer\Exception; $mail = new PHPMailer(true); // Passing `true` enables exceptions // Server settings $mail->SMTPDebug = false; // Enable verbose debug output $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = 'itachi.pw'; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = 'support@itachi.pw'; // SMTP username $mail->Password = '2@@1TesT1@~'; // SMTP password $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption, `ssl` also accepted $mail->Port = 587; // TCP port to connect to $success = ""; $error = ""; $name = $message = $email = ""; $errors = array('name' => '', 'email' => '', 'message' => ''); if (isset($_POST["submit"])) { $name = $_POST["name"]; $email = $_POST["email"]; $message = $_POST["message"]; try{ $mail->setFrom('support@itachi.pw', 'This is a test from Support'); $mail->addAddress($email, $name); $mail->Subject = 'Build a contact form with PHP'; $mail->Body = $message; // send mail $mail->send(); $name = $message = $email = ""; $success = "Message sent successfully"; } catch (Exception $e) { echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"; } } ?> <!DOCTYPE html> <html> <head> <script src="https://cdn.tailwindcss.com"></script> </head> <body> <div class="text-gray-400 bg-gray-900 body-font relative"> <form action="index.php" method="post"> <div class="container px-5 py-24 mx-auto"> <div class="flex flex-col text-center w-full mb-12"> <h1 class="sm:text-3xl text-2xl font-medium title-font mb-4 text-white">Contact Us</h1> <p class="lg:w-2/3 mx-auto leading-relaxed text-base">Whatever cardigan tote bag tumblr hexagon brooklyn asymmetrical gentrify.</p> </div> <div class="text-2xl font-medium title-font rounded text-green-400 text-center"><?php echo $success ?></div> <div class="text-2xl font-medium title-font rounded-full text-red-400 text-center"><?php echo $error ?></div> <div class="lg:w-1/2 md:w-2/3 mx-auto"> <div class="flex flex-wrap -m-2"> <div class="p-2 w-1/2"> <div class="relative"> <label for="name" class="leading-7 text-sm text-gray-400">Name</label> <input type="text" id="name" name="name" value="<?php echo htmlspecialchars($name) ?>" class="w-full bg-gray-800 bg-opacity-40 rounded border border-gray-700 focus:border-indigo-500 focus:bg-gray-900 focus:ring-2 focus:ring-indigo-900 text-base outline-none text-gray-100 py-1 px-3 leading-8 transition-colors duration-200 ease-in-out"> </div> </div> <div class="p-2 w-1/2"> <div class="relative"> <label for="email" class="leading-7 text-sm text-gray-400">Email</label> <input type="email" id="email" name="email" value="<?php echo htmlspecialchars($email) ?>" class="w-full bg-gray-800 bg-opacity-40 rounded border border-gray-700 focus:border-indigo-500 focus:bg-gray-900 focus:ring-2 focus:ring-indigo-900 text-base outline-none text-gray-100 py-1 px-3 leading-8 transition-colors duration-200 ease-in-out"> </div> </div> <div class="p-2 w-full"> <div class="relative"> <label for="message" class="leading-7 text-sm text-gray-400">Message</label> <textarea id="message" name="message" class="w-full bg-gray-800 bg-opacity-40 rounded border border-gray-700 focus:border-indigo-500 focus:bg-gray-900 focus:ring-2 focus:ring-indigo-900 h-32 text-base outline-none text-gray-100 py-1 px-3 resize-none leading-6 transition-colors duration-200 ease-in-out"><?php echo htmlspecialchars($message) ?></textarea> </div> </div> <div class="p-2 w-full"> <button type="submit" class="flex mx-auto text-white bg-indigo-500 border-0 py-2 px-8 focus:outline-none hover:bg-indigo-600 rounded text-lg" name="submit" id="submit">Send</button> </div> <div class="p-2 w-full pt-8 mt-8 border-t border-gray-800 text-center"> <a class="text-indigo-400">example@email.com</a> <p class="leading-normal my-5">49 Smith St. <br>Saint Cloud, MN 56301 </p> <span class="inline-flex"> <a class="text-gray-500"> <svg fill="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" class="w-5 h-5" viewBox="0 0 24 24"> <path d="M18 2h-3a5 5 0 00-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 011-1h3z"></path> </svg> </a> <a class="ml-4 text-gray-500"> <svg fill="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" class="w-5 h-5" viewBox="0 0 24 24"> <path d="M23 3a10.9 10.9 0 01-3.14 1.53 4.48 4.48 0 00-7.86 3v1A10.66 10.66 0 013 4s-4 9 5 13a11.64 11.64 0 01-7 2c9 5 20 0 20-11.5a4.5 4.5 0 00-.08-.83A7.72 7.72 0 0023 3z"></path> </svg> </a> <a class="ml-4 text-gray-500"> <svg fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" class="w-5 h-5" viewBox="0 0 24 24"> <rect width="20" height="20" x="2" y="2" rx="5" ry="5"></rect> <path d="M16 11.37A4 4 0 1112.63 8 4 4 0 0116 11.37zm1.5-4.87h.01"></path> </svg> </a> <a class="ml-4 text-gray-500"> <svg fill="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" class="w-5 h-5" viewBox="0 0 24 24"> <path d="M21 11.5a8.38 8.38 0 01-.9 3.8 8.5 8.5 0 01-7.6 4.7 8.38 8.38 0 01-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 01-.9-3.8 8.5 8.5 0 014.7-7.6 8.38 8.38 0 013.8-.9h.5a8.48 8.48 0 018 8v.5z"></path> </svg> </a> </span> </div> </div> </div> </div> </form> </div> </body> </html>
Output

Conclusion
By following these steps, you can easily set up a PHP script using PHPMailer to send emails from your website’s contact form. Make sure to customize the code according to your specific requirements, and feel free to enhance the form’s appearance and validation as needed.