How to send email using PHPMailer Library

Project: in this project we will learn how to send email using PHP Mailer which handle the mail very easily from web server.

PHPMailer : is a php library to send email easily from web server, phpmailer make easy process to send emails safely. To download phpmailer library click on link. Download PHPMailer .

SMTP : To send email we need to have SMTP We can buy SMTP online but here we will use Gmail SMTP for sending email.


index

myproject/index.php
index.php
              
                  <?php include("send.php"); ?>
                  <?php include("common/header.php"); ?>
                  <?php include("common/navbar.php"); ?>
                  <br>
                  <div class="container border w-50 p-2" style="margin-top: 10px;background:#f5f6fa;">
                    <h3 class="rounded bg-primary w-100 p-2 text-white text-center">Send Email</h3>
                      <div class="text-center"><?php echo $success;?><?php echo $error; ?></div>
                        <form method="POST" action="index.php" class="p-2 w-100">
                            <div class="form-group">
                              <label for="name">Full Name:</label>
                              <input type="text" class="form-control" name="fullname" id="fullname" placeholder="Enter Your Full Name">
                            </div>
                            <div class="form-group">
                              <label for="email">Sender Email Address :</label>
                              <input type="email" class="form-control" name="sender_email" id="sender_email" placeholder="Sender: exampl@gmail.com">
                            </div>
                            <div class="form-group">
                              <label for="email">Recipient Email Address :</label>
                              <input type="email" class="form-control" name="recipient_email" id="recipient_email" placeholder="Reciever :exampl@gmail.com">
                            </div>
                            <div class="form-group">
                              <label for="subject">Subject :</label>
                              <input type="text" class="form-control" name="subject" id="subject" placeholder="subject">
                            </div>
                            <div class="form-group">
                              <label for="msg">Message :</label><br>
                              <textarea name="message" id="message" cols="78" rows="3" class="form-control" placeholder="Write Your Message Here"></textarea>
                            </div> 
                            <div class="form-group">
                              <input type="submit" name="send" id="submit" value="Send Email" class="btn btn-primary">
                              <a href="#" class="btn btn-danger float-right">Close</a> 
                            </div>          
                        </form>
                      </div><br>
                  <?php include("common/footer.php"); ?
                
            

Create Database and Table

Create table in database

PHP
Create connection with database
myproject/dbcon.php
dbcon.php
    
        $dbhost ="localhost";
        $dbuser ="root";
        $dbpswd ="";
        $dbname ="dbdemo";
        $dbcon= mysqli_connect($dbhost,$dbuser,$dbpswd,$dbname);
        if($dbcon){
            //echo "Connected............!!!";
            return $dbcon;
            exit();
        }else{
            die("Connection failed ? ? ?". mysqli_error($dbcon));
        }
        mysqli_close($dbcon);
    

Process to send email with phpmailer

myproject/send.php
send.php
              
                <?php include("dbcon.php");
                $dbcon = mysqli_connect('localhost','root','','dbdemo');
                //This is phpmailer library , you can get this library on github
                require ('phpmailer/PHPMailerAutoload.php'); 
                $success=''; $error='';
                if(isset($_POST['send'])){
                    $fullname = filter_var(ucwords( $_POST['fullname']),FILTER_SANITIZE_STRING);
                    $sender_email   = filter_var($_POST['sender_email'],FILTER_SANITIZE_EMAIL);
                    $recipient_email= filter_var($_POST['recipient_email'],FILTER_SANITIZE_EMAIL);
                    $subject  = filter_var($_POST['subject'],FILTER_SANITIZE_STRING);
                    $message  = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
                    if(empty($fullname) || empty($sender_email) || empty($recipient_email) || empty($subject) || empty($message)){
                        $error ="<div class='alert alert-danger'>All the fields are required</div>";
                    }else if (!preg_match("/^[a-zA-Z][a-zA-Z\\s]+$/", $fullname)){
                        return "inavlid_name";
                        $error ="<div class='alert alert-danger'>The email has been failed to send</div>";
                    }else if(!filter_var( $sender_email,FILTER_VALIDATE_EMAIL)) {
                        $error ="<div class='alert alert-danger'>The sender email address is invalid</div>";
                    }else if(!filter_var( $recipient_email,FILTER_VALIDATE_EMAIL)) {
                        $error ="<div class='alert alert-danger'>The recipient email address is invalid</div>";
                    }else if (!preg_match("/^[a-zA-Z][a-zA-Z\\s]+$/", $subject)) {
                        $error ="<div class='alert alert-danger'>Only alphabets are allowed in subject field</div>";
                    }else if (strlen($subject) < 4 ){
                        $error ="<div class='alert alert-danger'>The subject must be minimum 4 characters</div>";
                    }else{         
                        
                        $sql= "INSERT INTO `email` (`fullname`, `sender_email`,`recipient_email`, `subject`, `message`) VALUES('$fullname','$sender_email','$recipient_email','$subject','$message')";
                        $run = mysqli_query($dbcon, $sql);
                        if($run){
                            //=to send email to user
                            // Instantiation and passing `true` enables exceptions
                            $mail = new PHPMailer();
                            //Server settings
                            //$mail->SMTPDebug = 4;                                                        
                            $mail->isSMTP();                      
                            $mail->Host = 'smtp.gmail.com'; // here you need config your smtp, I am using gmail   
                            $mail->SMTPAuth = true;               
                            $mail->Username = 'xxxxxxx@gmail.com'; // your email address  
                            $mail->Password = '..........';  // your password of email account on gmail, yahoo etc
                            $mail->SMTPSecure = 'ssl';          
                            $mail->Port = 465;            
                                                
                            $mail->setFrom($sender_email, $fullname);
                            $mail->addAddress($recipient_email, "Uknown");     
                            //$mail->addAddress('cc@example.com');              
                            $mail->addReplyTo('nonreply@oursystem', 'Our System');
                            //$mail->addCC('cc@example.com');
                            //$mail->addBCC('bcc@example.com'); 
                            $mail->isHTML(true);                               
                            $mail->Subject = $subject;
                            $mail->Body    = $message;
                            // $mail->Subject = 'Greeting from Smart Infotechsys';
                            // $mail->Body    = "<h3>Hello  " .$fullname."</h3><br><p>How are you <p> Best Regards <br> Our Team <br> Smart Infotechsys </p> ";
                            if(!$mail->send()){
                                $error="<div class='alert alert-danger'><span style='color:red;'>The email could not be sent !Please check you email address !</span></div>";
                                $error="<div class='alert alert-danger'>Mailer Error:". $mail->ErrorInfo."</div>";
                            } else {
                                $success="<div class='alert alert-success'><span style='color:green;'>The email has been sent to {$recipient_email}</span></div>";
                            }
                        }
                    }         
                }
              
            
When you click on button "SendEmail" email will be sent from localhost server If email sending being failed check your email account inbox You need to take permission from your email smtp permisiion such as like from google if you are using gmail smtp. We will fix this problem check below and folllow. The Error will be displayed something like that. Mailer Error : SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/..... Because the email is being blocked from your email smtp permission.

Mail Error for Email Sending Failed (Solve Errors).

This is SMTP Connection error because its not getting permission from your mail account. Lets fix this problem, We have to set configuration in google SMTP email setting. We need to follow for google email SMTP connection.
PHP

Check Your Email Account Inbox

Critical Security for Email

Click on check activity
PHP

Permission from Google Account

Less Secure App

Click on learn more
PHP

Permission from Google Account

Less Secure App

Click on: if "Less secure app" is on for your account.
Then click on: Go to the Less secure app access.
PHP

Permission from Google Account

Less secure spp Access

Allow less secure app : OFF Just ON it
PHP

Check below

PHP

Send Email Again

Now email will be sent to recipient.

If any other error, check your code and try to solve the errors (solving errors by yourself will teach you many things)
PHP

common

header.php
    
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1,
            shrink-to-fit=no">
            <title>Codetechinfo</title>
            <link rel="stylesheet" href="css/bootstrap.min.css">
        </head>
    
navbar.php
    
        <nav class="navbar navbar-expand-lg navbar-light bg-primary text-white fixed-top">
            <a class="navbar-brand text-white" href="./index.php">Learn PHP  </a>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav">
                    <li class="nav-item active">
                        <a class="nav-link text-white" href="./index.php">Home  </a>
                    </li> 
                </ul>
            </div>
        </nav>
        <br><br>
    
footer.php
    
            <div class="copyright py-4 text-center text-white">
                <div class="container "><small>© Copyright 2025 by Saten Chauhan</small> </div>
            </div>
            </body>
        </html>
    

css folder

You must download and include bootstrap css source files for good interface OR You can add cdn link from bootstrap website.
myproject/css
bootstrap.min.css