In this tutorial we will send email to multiple person via checkbox it will automatically put all the users email and send one by one to checked users


PHPMailer library allows to send emails before you start tutorial we need to install PHP library via composer command run the following command to install PHPmailer.

composer require phpmailer/phpmailer

once you run following command it will automatically download all the the necessary files and create autoload.php file


Database structure

-- phpMyAdmin SQL Dump
-- version 5.0.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Apr 12, 2020 at 07:55 AM
-- Server version: 10.4.11-MariaDB
-- PHP Version: 7.2.28

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `multiple_checkbox_email`
--

-- --------------------------------------------------------

--
-- Table structure for table `signup`
--

CREATE TABLE `signup` (
  `id` int(11) NOT NULL,
  `username` text NOT NULL,
  `email` text NOT NULL,
  `member_since` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Dumping data for table `signup`
--

INSERT INTO `signup` (`id`, `username`, `email`, `member_since`) VALUES
(1, 'test', 'gajanand.kgn@gmail.com', '0000-00-00'),
(2, 'stint', 'gajanand.kgn@rediffmail.com', '0000-00-00');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `signup`
--
ALTER TABLE `signup`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `signup`
--
ALTER TABLE `signup`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

#init.php

<?php
define("DB_NAME", "multiple_checkbox_email");
define("DB_USER", "root");
define("DB_HOST", "localhost");
define("DB_PASS", "");
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

#index.php

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <!-- Latest compiled and minified CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css?ver=0.6" rel="stylesheet">
        <link href="plugins/trumbowyg/trumbowyg.min.css" rel="stylesheet" type="text/css"/>
        <style>
            .msg_container {
                position: fixed;
                width: 470px;
                right: 0;
                bottom: 0;
                background: #f7efef;
                padding: 15px;
                border-radius: 2px;   
                color: #000;
                box-shadow: -2px -5px 20px 0px #00000040;


            }

            .msg_container h4{
                margin-top: 0;

            }
            
            .trumbowyg-editor, .trumbowyg-textarea {
                min-height: 200px;
            }

        </style>
    </head>
    <body>
        <?php
        include 'init.php';
        include 'vendor/autoload.php';
        // Get count of data set first
        $sql = "SELECT * FROM `signup`";
        $count = $conn->query($sql)->num_rows;

        // Initialize a Data Pagination with previous count number
        $pagination = new \yidas\data\Pagination([
            'totalCount' => $count,
            'pergpage' => 10,
        ]);

        // Get range data for the current page
        $sql = "SELECT * FROM `signup` LIMIT {$pagination->offset}, {$pagination->limit}";
        $users = $conn->query($sql);
        ?>


        <table class="table table-striped">
            <thead>
                <tr>
                    <th>
                        <input type="checkbox" id="mcheck"> Check All
                    </th>
                    <th>Username</th>
                    <th>Email</th>
                    <th>Registered on</th>
                </tr>
            </thead>
            <tbody id="alluser">
                <?php while ($user = $users->fetch_assoc()): ?>



                    <tr>
                        <td>
                            <input type="checkbox" value="<?php echo $user['email']; ?>" onclick="updateTextArea();">
                        </td>
                        <td><?php echo $user['username']; ?></td>
                        <td><?php  echo $user['email']; ?>
                        </td>
                        <td><?php echo $user['member_since']; ?></td>
                    </tr>

                <?php endwhile; ?>
            </tbody>
        </table>
        <div>
            <?php
            \yidas\widgets\Pagination::widget([
                'pagination' => $pagination
            ])
            ?>
        </div>
        <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
        <script src="plugins/trumbowyg/trumbowyg.min.js" type="text/javascript"></script>
        <script src="main.js" type="text/javascript"></script>
      

        <form action="" method="post" class="msg_container">
            <h4>Compose Email</h4>
            <p id="multi-responce"></p>
            <div class="form-group">
                <textarea class="form-control" id="emails" name="emails" placeholder="Email list" style="height: 120px;"></textarea>
            </div>
            <div class="form-group">
                <input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" required>
            </div>
            <div class="form-group">
                <textarea style="height: 220px;" id="message" name="message" class="form-control" placeholder="Your Message" rows="5" required></textarea>
            </div>
            <button type="button" onclick="multi_email();" class="btn btn-primary btn-lg col-lg-12" id="send">Send Now </button>

        </form>
         
    </body>
</html>

#main.js

$(document).ready(function() {

    $('#message').trumbowyg();

    $("#mcheck").on('click', function() {
        $('input:checkbox').not(this).prop('checked', this.checked);

    });

});

function updateTextArea() {
    var allVals = [];
    $('#alluser tr td :checked').each(function() {
        allVals.push($(this).val());
    });
    $('#emails').val(allVals);
}
$(function() {
    $('#mcheck').click(updateTextArea);
    updateTextArea();
});


function multi_email() {

    $('#multi-responce').html("Sending to <span id='curent-email'></span>");
    var emails = $('#emails').val();
    var subject = $('#subject').val();
    var message = $('#message').val();

    var path_uri =  "multiemails.php";

    var email = emails.split(',');



    $.ajax({
        type: "POST",
        url: path_uri,
        data: {
            emails: email_loop(email),
            subject: subject,
            message: message
        },
        success: function(data) {
            if (data == "success") {
                $('#multi-responce').html("Successfully sent");

            } else {
                $('#multi-responce').html(data);
            }
        }
    });
}




var i = 0;
function email_loop(emails) {
    var email = emails[i];
    $("#curent-email").html(email);
    if (++i < emails.length) {
        setTimeout(multi_email, 1000);
    }

    return email;
}

#multiemails.php

<?php
include 'SMTPMailer.php';
$subject = $_POST['subject'];
$email = $_POST['emails'];
$message = $_POST['message'];
$smtp = new SMTPMailer();
$mail = $smtp->load();

foreach (explode(",", $email) as $address) {

    //call phpmailerlibrary class here 
    $mail->addAddress($address, "Hello");
    $mail->Subject = $subject;
    $mail->Body = $message;
    if ($mail->send()) {
        echo "success";
    } else {
        echo $mail->ErrorInfo;
    }
}
?>

#output: