DEV Community

Cover image for How to Send HTML Form via PHP Mailer
HMA WebDesign
HMA WebDesign

Posted on

How to Send HTML Form via PHP Mailer

What is PHP Mailer?

Before we dive into the details, let’s briefly introduce PHP Mailer. PHP Mailer is a robust PHP library that simplifies the process of sending emails through PHP scripts. It offers an intuitive and feature-rich interface for sending plain text and HTML emails, complete with attachments and more.

Steps – Send HTML Form via PHP Mailer

Let’s start with a detailed outline that will guide us to Send HTML Form via PHP Mailer through this extensive guide. Here are the important steps to Send an HTML Form via PHP Mailer on HTML form submission:

  1. Download and install PHP Mailer from GitHub
  2. Setup your HTML Contact Form
  3. Include PHP Mailer in your HTML code
  4. Configure PHP Mailer
  5. Process form data to send email
  6. Compose the Email
  7. Handle Success and Error messages
  8. Send the Email
  9. Video Tutorial – Send HTML Form via PHP Mailer
  10. Now that we have our roadmap, let’s explore each section in detail to Send HTML Form via PHP Mailer.

How to Send HTML Form to Email Using PHP Mailer

Sending HTML forms via email is a seamless process when you have PHP Mailer at your disposal. Here’s a step-by-step guide to achieving, how to send HTML form via PHP Mailer:

Prerequisites

Before diving into implementation, ensure that you have the following prerequisites in place:

A Web Server with PHP Support: You’ll need a web server, such as Apache or Google, with PHP support to run your PHP Mailer script.
Email Server Access: Ensure you have access to an email server or SMTP server to send emails, such as Gmail.
Basic HTML and PHP Knowledge: Familiarize yourself with HTML to create the form and PHP to process it.

Step by Step Video Tutorial:

Getting Started

Let’s start by downloading PHP Mailer and setting up our HTML form to Send HTML Form via PHP Mailer:

1. Download and install PHP Mailer
Begin by downloading the PHP Mailer library. You can obtain it from the official GitHub repository or use Composer if you prefer package management.

To Download the PHP Mailer manually from the GitHub library Click Here!

If you want to install the PHPMailer using Composer. First of all, simply install the Composer Setup on your computer and run the following command in your terminal:

composer require phpmailer/phpmailer

Alternatively, if you’re not using Composer, you can download PHPMailer as a zip file, and then copy the contents of the PHPMailer folder into one of the include_path directories specified in your PHP configuration and load each class file manually:

2. Set Up Your HTML Form
Create an HTML form on your website where users can submit their information. Ensure that your form fields have appropriate name attributes.

HTML Form Source Code

I have created a simple HTML form to send web form data to email using PHPMailer. I will collect this form data from the user and send it to my email address using PHPMailer.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    @import url(https://fonts.googleapis.com/css?family=Open+Sans:400italic,400,300,600);

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      font-weight: 300;
      font-size: 12px;
      line-height: 30px;
      color: #272727;
      background: rgb(25, 199, 155);
    }

    .container {
      max-width: 400px;
      width: 100%;
      margin: 0 auto;
      position: relative;
    }

    #contact input {
      font: 400 12px/16px;
      width: 100%;
      border: 1px solid #CCC;
      background: #FFF;
      margin: 10 5px;
      padding: 10px;
    }

    h1 {
      margin-bottom: 30px;
      font-size: 30px;
    }

    #contact {
      background: #F9F9F9;
      padding: 25px;
      margin: 50px 0;
    }


    fieldset {
      border: medium none !important;
      margin: 0 0 10px;
      min-width: 100%;
      padding: 0;
      width: 100%;
    }

    textarea {
      height: 100px;
      max-width: 100%;
      resize: none;
      width: 100%;
    }

    button {
      cursor: pointer;
      width: 100%;
      border: none;
      background: rgb(17, 146, 60);
      color: #FFF;
      margin: 0 0 5px;
      padding: 10px;
      font-size: 20px;
    }

    button:hover {
      background-color: rgb(15, 95, 42);
    }
  </style>
</head>

<body>
  <div class="container">
    <form id="contact" action="mail.php" method="post">
      <h1>Contact Form</h1>

      <fieldset>
        <input placeholder="Your name" name="name" type="text" tabindex="1" autofocus>
      </fieldset>
      <fieldset>
        <input placeholder="Your Email Address" name="email" type="email" tabindex="2">
      </fieldset>
      <fieldset>
        <input placeholder="Type your subject line" type="text" name="subject" tabindex="4">
      </fieldset>
      <fieldset>
        <textarea name="message" placeholder="Type your Message Details Here..." tabindex="5"></textarea>
      </fieldset>

      <fieldset>
        <button type="submit" name="send" id="contact-submit">Submit Now</button>
      </fieldset>
    </form>
  </div>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

3. Include PHP Mailer
In your PHP script, include the PHP Mailer library using require or require_once. as shown in the following script:

4. Configure PHP Mailer
Set up PHP Mailer with your email server details, including the SMTP host, username, password, and port. Make sure to use valid credentials and a secure connection.

If you are using a Gmail SMTP server, first of all, login to your Gmail ID, turn on 2-step authentication and, generate an App Password. To generate an App Password in your Gmail account follow this link.

5. Process Form Data
In your PHP script, retrieve the form data submitted by the user using $_POST or $_GET, depending on your form’s method attribute. In this tutorial, we have received the following form data from the user:

6. Compose the Email
Use PHP Mailer to compose your email. You can format it as plain text or HTML, depending on your preference. Here is the complete PHPMailer source code to send HTML form via PHP Mailer:

PHPMailer Source Code

Copy the below source code and change the data according to your preferences:

<?php

//Import PHPMailer classes into the global namespace
//These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

//required files
require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';

//Create an instance; passing `true` enables exceptions
if (isset($_POST["send"])) {

  $mail = new PHPMailer(true);

    //Server settings
    $mail->isSMTP();                              //Send using SMTP
    $mail->Host       = 'smtp.gmail.com';       //Set the SMTP server to send through
    $mail->SMTPAuth   = true;             //Enable SMTP authentication
    $mail->Username   = 'your email address';   //SMTP write your email
    $mail->Password   = 'app password';      //SMTP password
    $mail->SMTPSecure = 'ssl';            //Enable implicit SSL encryption
    $mail->Port       = 465;                                    

    //Recipients
    $mail->setFrom( $_POST["email"], $_POST["name"]); // Sender Email and name
    $mail->addAddress('example@gmail.com');     //Add a recipient email  
    $mail->addReplyTo($_POST["email"], $_POST["name"]); // reply to sender email

    //Content
    $mail->isHTML(true);               //Set email format to HTML
    $mail->Subject = $_POST["subject"];   // email subject headings
    $mail->Body    = $_POST["message"]; //email message

    // Success sent message alert
    $mail->send();
    echo
    " 
    <script> 
     alert('Message was sent successfully!');
     document.location.href = 'index.php';
    </script>
    ";
}
?>
Enter fullscreen mode Exit fullscreen mode

7. Handle Success and Error messages
Implement error handling to deal with scenarios where the email-sending process might fail. Display a success message to the user upon successful submission.

8. Send the Email
Use the send method to send the email. Ensure to implement error handling to deal with scenarios where the email-sending process might fail.

9. Testing Your Setup
After implementing the above steps, thoroughly test your setup. Submit test data through your HTML form to ensure that emails are being sent correctly to the specified email address.

Conclusion
In conclusion, PHP Mailer is a powerful tool that simplifies the process of sending HTML forms to email addresses. By following the steps outlined in this guide, you can enhance user interaction on your website and efficiently collect user information, feedback, and inquiries. Remember to handle errors gracefully and ensure the security of user data during transmission.

Now, let’s address some frequently asked questions (FAQs) related to PHP Mailer and email functionality.

Top comments (1)

Collapse
 
magma profile image
Mr

im stupid cuz i dont know how to open php file