How to send email using SwiftMailer Library

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

SwiftMailer : is a component based php library send email easily from web server, SwiftMailer make easy to handle emailing process. To download swiftmailer library click on link. Download SwiftMailer .

Vendor folder will add automatically when you install php swiftmailer library .

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

cmd or Gitbash User@User MINGW64 /c/xampp/htdocs/myproject
$ composer require "swiftmailer/swiftmailer:^6.0"

Send Form

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 swiftmailer

myproject/send.php
send.php
              
                <?php include("dbcon.php");
                $success=''; $error='';
                //Vendor is SwiftMailer library
                require_once ('vendor/autoload.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
                            $transport = (new Swift_SmtpTransport('smtp.gmail.com', 465, 'ssl'))
                              ->setUsername('...........@gmail.com')// your username of SMTP or email address (demo@demo.gmail.com)
                              ->setPassword('............'); //password of SMTP or email account like gmail or yahoo etc.
                            // Create the Mailer using your created Transport
                            $mailer = new Swift_Mailer($transport);
                            // Create a message
                            $body_msg = (new Swift_Message($subject))
                              ->setFrom([$sender_email => $fullname])
                              ->setTo($recipient_email)
                              ->setBody($message, 'text/html');
                            // Send the message
                            $result = $mailer->send($body_msg);
                            if($result){
                                $success="<div class='alert alert-success'><span style='color:green;'>The email has been sent to {$recipient_email}</span></div>";
                            } else {
                                $error="<div class='alert alert-danger'><span style='color:red;'>The email could not be sent !Please check you email address !</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. You can fix this problem check below. The Error will be displayed something like that. Mailer Error:SMTP connect() failed... Troubleshooting 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 a lot)
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