Send an HTML mail through PHP Mailer and localhost

Send an HTML mail through PHP Mailer and localhost

PHP Mailer is the most widely used library to send mail because sending emails through PHP mailer is easy and safe. In this blog, we’ll send mail using Xampp as a local server, Gmail SMTP and PHP Mailer. The Simple Mail Transfer Protocol (SMTP) is an internet standard communication protocol for electronic mail transmission. Mail servers and other message transfer agents use SMTP to send and receive mail messages.

Download and basic setup:

Let’s get started! At first, we’ll download the required files for using PHP Mailer. Go to the official GitHub repo of PHP Mailer. Click on the code dropdown and download the zip file of the library. Extract the contents of the zip file in the folder you desire.

Create a folder named ‘PHPMailer’ in your project folder (inside htdocs in xampp). Copy the ‘PHPMailer.php’, ‘SMTP.php', and 'Exception.php’ files inside the 'src’ folder in the extracted folder to the new folder you created.

Localhost settings:

Navigate to php\php.ini inside the xampp folder in your local drive.

Use ctrl + f to find the below values and update them

SMTP=smtp.gmail.com

smtp_port=587

sendmail_from = YourGmailId@gmail.com

sendmail_path = "\"D:\xampp\sendmail\sendmail.exe\" -t"

NOTE: There is a space before -t. Make sure to replace the contents according to your mail, requirement, and the location of your folder.

Navigate to sendmail\sendmail.ini inside the xampp folder in your local drive.

Use ctrl + f to find the below values and update them

smtp_server=smtp.gmail.com

smtp_port=587

error_logfile=error.log

debug_logfile=debug.log

auth_username=YourGmailId@gmail.com

auth_password=YourGmailPassword

force_sender=YourGmailId@gmail.com

NOTE: force_sender is optional

GMAIL settings:

Go to your google account and turn on less secure apps access.

Links that fix the problem if the mail isn’t sent even after less secure apps access is turned on (you must be logged into a Google account):

https://security.google.com/settings/security/activity?hl=en&pli=1

https://accounts.google.com/b/0/DisplayUnlockCaptcha

Creating a simple form:

Fig: View of form page in a browser

Create an ‘index.html’ file inside your project folder and copy the code snippets below.

<!DOCTYPE html>

<html lang="en">

  <head>

    <!-- Required meta tags -->

    <meta charset="utf-8" />

    <meta

      name="viewport"

      content="width=device-width, initial-scale=1, shrink-to-fit=no"

    />

    <!-- Bootstrap CSS -->

    <link

      rel="stylesheet"

      href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"

      integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"

      crossorigin="anonymous"

    />

    <title>PHP Mailer</title>

    <style>

      .center {

        positionabsolute;

        left50%;

        top50%;

        transformtranslate(-50%-50%);

        padding10px;

      }

    </style>

  </head>

The above code contains few meta tags and links to external CSS. The style tag ensures the content of the body is at the center of the page.                                                                                           

  <body>

    <div class="text-center">

      <h1>Sending email using PHP Mailer</h1>

    </div>

    <div class="center col-lg-6">

      <div id="error"></div>

      <form id="mail-form" enctype="multipart/form-data">

        <div class="form-group">

          <label for="sendfrom">Set Mail From: </label><br />

          <input

            type="text"

            name="sendfrom"

            id="sendemail"

            class="form-control"

            required=""

          />

        </div>

        <div class="form-group">

          <label for="sentmail">Set Mail To: </label><br />

          <input

            type="text"

            name="sendto"

            id="sendmailto"

            class="form-control"

            required=""

          />

        </div>

        <div class="form-group">

          <label for="sentmail">Add reply to: </label><br />

          <input

            type="text"

            name="replyto"

            id="replyemail"

            class="form-control"

            required=""

          />

        </div>

        <div class="form-group">

          <label for="Subjectofmail">Subject of mail:</label>

          <input

            type="text"

            class="form-control"

            name="subject"

            id="Subjectofmail"

            required

          />

        </div>

        <div class="form-group">

          <label for="Bodyofmail">Body of mail:</label>

          <textarea

            class="form-control"

            name="body"

            id="Bodyofmail"

            required

          ></textarea>

        </div>

        <button class="submit" type="submit" id="submit-form">Submit</button>

      </form>

    </div>

The above code has a form with few input fields and submit button to submit form details.

    <!-- Optional JavaScript -->

    <!-- jQuery first, then Popper.js, then Bootstrap JS -->

    <!-- Jquery JS-->

    <script

      src="https://code.jquery.com/jquery-3.5.1.js"

      integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="

      crossorigin="anonymous"

    ></script>

    <script

      src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"

      integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"

      crossorigin="anonymous"

    ></script>

    <script

      src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"

      integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"

      crossorigin="anonymous"

    ></script>

    <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>

The below script tag ensures that the input fields follow the correct format and ensures every required field is filled before submitting the form.

    <script>

      $(document).ready(function () {

        const mailformat = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

        $("#sendemail").keyup(function () {

          var sendmailfrom = $("#sendemail").val();

          if (!sendmailfrom.match(mailformat)) {

            $("#error").html(

              '<div style="background-color:#ff6666;height:40px;padding : 6px;color:white;">Not a valid email address in send from</div>'

            );

            return false;

          } else {

            $("#error").html(

              '<div style="background-color:#4dff88;height:40px;padding : 6px;">Valid Email Adress</div>'

            );

          }

        });

        $("#sendmailto").keyup(function () {

          var sendmailfrom = $("#sendmailto").val();

          if (!sendmailfrom.match(mailformat)) {

            $("#error").html(

              '<div style="background-color:#ff6666;height:40px;padding : 6px;color:white;">Not a valid email address in send from</div>'

            );

            return false;

          } else {

            $("#error").html(

              '<div style="background-color:#4dff88;height:40px;padding : 6px;">Valid Email Adress</div>'

            );

          }

        });

        $("#replyemail").keyup(function () {

          var addreply = $("#replyemail").val();

          if (!addreply.match(mailformat)) {

            $("#error").html(

              '<div style="background-color:#ff6666;height:40px;padding : 6px;color:white;">Not a valid email address in add reply to</div>'

            );

            return false;

          } else {

            $("#error").html(

              '<div style="background-color:#4dff88;height:40px;padding : 6px;">Valid Email address</div>'

            );

          }

        });

        $("#submit-form").click(function (e) {

          e.preventDefault();

          var fd = new FormData(document.getElementById("mail-form"));

          if (

            $("#sendemail").val() != "" &&

            $("#Subjectofmail").val() != "" &&

            $("#Bodyofmail").val() != "" &&

            $("#replyemail") != ""

          ) {

            $("#submit-form").prop("disabled"true);

            // console.log(sendmailfrom+" "+Subjectofmail+" "+Bodyofmail+" "+addreply+" "+attachment+" "+fd);

After the submit button is clicked, it gets disabled until it receives a response.

We make an ajax request to ‘mail.php’.

            $.ajax({

              url"./mail.php",

              datafd,

              type"post",

              contentTypefalse,

              processDatafalse,

              successfunction (result) {

                console.log(result);

                if (result == "success") {

                  swal("Mail sent""""success").then((value=> {

                    $("#submit-form").prop("disabled"false);

                  });

                } else if (result == "Email Empty") {

                  $("#error").html(

                    '<div style="background-color:#ff6666;color:white;height:40px;padding:10px;width:100%;border-radius:10px;">Mail Not found</div>'

                  );

                  $("#submit-form").prop("disabled"false);

                } else if (result == "Fields empty") {

                  $("#error").html(

                    '<div style="background-color:#ff6666;color:white;height:40px;padding:10px;width:100%;border-radius:10px;">Fields empty</div>'

                  );

                  $("#submit-form").prop("disabled"false);

                } else {

                  $("#error").html(

                    '<div style="background-color:#ff6666;height:40px;padding:10px;width:50%;border-radius:10px;">' +

                      result +

                      "</div>"

                  );

                  $("#submit-form").prop("disabled"false);

                }

              },

            });

          } else {

            $("#error").html(

              '<div style="background-color:#ff6666;height:40px;padding:10px;width:50%;border-radius:10px;">Fill out all the fields</div>'

            );

          }

        });

      });

    </script>

  </body>

</html>

The response received is displayed in the div below the heading if it is an error.

Send mail with HTML content:

In the same folder create a file named ‘mail.php' and copy-paste the code below.

<?php

require 'PHPMailer/Exception.php';

require 'PHPMailer/PHPMailer.php';

require 'PHPMailer/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;

use PHPMailer\PHPMailer\SMTP;

use PHPMailer\PHPMailer\Exception;

The above lines will import the required files.

The code doesn’t execute unless it receives the required details from contact form. (Read the comments for knowing what each line does)

if(isset($_POST['sendfrom']) && isset($_POST['sendto']) && isset($_POST['subject'])&& isset($_POST['body']) && isset($_POST['replyto']))

{

    $sendfrom = $_POST['sendfrom'];

    $sendto = $_POST['sendto'];

    $subject = $_POST['subject'];

    $body = $_POST['body'];

    $replyto = $_POST['replyto'];

    

    $altbody = $body;

    $body = trim($body);

    // temporarily replace two or more consecutive newlines

    // into SOH characters (not used in normal texts)

    $body = preg_replace('~(\\r\

    |\

    ){2,}|$~'"\\001", $body);

    // convert remaining (i.e. single) newlines into html br's

    $body = nl2br($body);

    // finally, replace SOH chars with paragraphs

    $body = preg_replace('/(.*?)\\001/s'"<p>$1</p>\

    ", $body);

    if (!empty($sendfrom) && !empty($sendto)){

        $mail = new PHPMailer();

        // $mail->SMTPDebug = 2; // 0 = off (for production use) - 1 = client messages - 2 = client and server messages

        $mail->SMTPDebug = 0;

        

        $mail->isSMTP(); 

        // add multiple hosts by seperating them with semicolon example: "smtp.gmail.com;domain.com"

        $mail->Host = "smtp.gmail.com"

        //Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission

        $mail->Port = 587

        //Set the encryption system to use - ssl (deprecated) or tls

        $mail->SMTPSecure = 'tls'

        //Whether to use SMTP authentication

        $mail->SMTPAuth = true;

           

          //Replace with your Gmail id

        $mail->Username = 'yourmail@gmail.com';

        //Replace with your Gmail password

        $mail->Password = 'gmailPassword';

          //Set who the message is to be sent from

        $mail->setFrom($sendfrom'sender name');

        //Set who the message is to be sent to

        $mail->addAddress($sendto);

        //Set an alternative reply-to address

        $mail->addReplyTo($replyto'sender');

        $mail->Subject = $subject;

        // add embbed image 

        $mail->AddEmbeddedImage('img/banner.jpg','cover_img');

        $mail->AddEmbeddedImage('img/fb.png','fb');

        $mail->AddEmbeddedImage('img/insta.png','insta');

Fig: View of the Mail in inbox (the text is received from input field)

      //Body of Email – HTML version

        $bodyOfMsg = '<table role="presentation" border="0" cellpadding="0" cellspacing="0" width="100%">

            <tr>

              <td style="padding: 20px 0 30px 0;">

        

        <table align="center" border="0" cellpadding="0" cellspacing="0" width="600" style="border-collapse: collapse; border: 1px solid #cccccc;">

          <tr>

            <td align="center" style="padding: 0 0 30px 0;">

              <img src="cid:cover_img" alt="Cover image" style="display: block;" />

            </td>

          </tr>

          <tr>

            <td bgcolor="#ffffff" style="padding: 40px 30px 40px 30px;">

              <table border="0" cellpadding="0" cellspacing="0" width="100%" style="border-collapse: collapse;">

                

                <tr>

                  <td style="color: #153643; font-family: Arial, sans-serif; font-size: 16px; line-height: 24px; padding: 20px 0 30px 0;">

                    <p style="margin: 0;">'.$body.'</p>

                  </td>

                </tr>

              </table>

            </td>

          </tr>

          <tr>

            <td bgcolor="#ee4c50" style="padding: 30px 30px;">

                <table border="0" cellpadding="0" cellspacing="0" width="100%" style="border-collapse: collapse;">

                <tr>

                  <td style="color: #ffffff; font-family: Arial, sans-serif; font-size: 14px;">

                    <p style="margin: 0;">&reg; Your company<br/>

                   Tagline goes here </p>

                  </td>

                  <td align="right">

                    <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse;">

                      <tr>

                        <td>

                          <a href="#">

                            <img src="cid:fb" alt="Facebook" width="38" height="38" style="display: block;" border="0" />

                          </a>

                        </td>

                        <td style="font-size: 0; line-height: 0;" width="20">&nbsp;</td>

                        <td>

                          <a href="#">

                            <img src="cid:insta" alt="Instagram" width="38" height="38" style="display: block;" border="0" />

                          </a>

                        </td>

                      </tr>

                    </table>

                  </td>

                </tr>

              </table>

            </td>

          </tr>

        </table>

        

              </td>

            </tr>

          </table>

        ';

        //To send html mail

        $mail->msgHTML($bodyOfMsg); 

        // If html emails is not supported by the receiver, then this body is shown

        $mail->AltBody = $altbody

        // print_r($mail);

        if(!$mail->send()){

            echo $mail->ErrorInfo;

        }else{

            echo "success";

        }

    }else{

        echo "Email Empty";

}

}else{

    echo "Fields empty";

}

Run the code by navigating to your project folder in your browser (example:  http://localhost/test-mail/ )

After filling in the respective details in the form and clicking on the submit button, the button gets disabled until it receives a response. If the credentials were correct and you followed all the steps accordingly, your mail will be sent, and you'll receive a pop-up.

Voila! You made it till the end. Hope you gained some insights about how to send mail using PHP Mailer.

 

This blog has been submitted by Cyborg, NIT Rourkela under the Robocraze Club Outreach Program.

Author: Divya Sri Darimisetti

Leave a comment

Please note, comments must be approved before they are published