Tuesday, 17 October 2017

How to Send Bulk Email in PHP using PHPMailer with Ajax JQuery



Most of the Website has the sending of email feature like send single email or bulk email. So In this post we have discuss topic like how can we send bulk email by using PHP script with PHPMailer Ajax and Jquery. We have use PHPMailer Library because PHP mail() function will not work on localhost. So we have discuss how can we send single or bulk email from localhost in PHP with PHPMailer by using Ajax Jquery. So we can send single or bulk email without refresh or webpage.

We have use SMTP for send bulk mail because SMTP us the most suggested way to send email from localhost or online server. If we have use SMTP to send mail so PHP has nice library PHPMailer library which allow to send email via SMTP by providing required credential. If you have any web hosting email account then your hosting company will provide SMTP credential like username, password, outgoing and incoming server address and port number. By using this information you can configured this details into PHPMailer class and then after you can send email from your script.

In this post we have make simple application from which we can send bulk email to customer by single click. Here we have use Jquery with Ajax so we can send email without refresh of web page. When we have click on button then it will collect email from checkboxes data attribute by using Jquery and after collecting data it will send this data to Ajax request and via Ajax request it will transfer to PHP script and in this we have use PHPMailer class with required SMTP configuration and it will send bulk email and after sending all email successfully it will send data to Ajax request and it will display on web page. This way we can use Ajax with Jquery for Send bulk email by using PHP with PHPMailer Library.









Source Code


index.php



<?php
//index.php
$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
$query = "SELECT * FROM customer ORDER BY customer_id";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
?>
<!DOCTYPE html>
<html>
 <head>
  <title>Send Bulk Email using PHPMailer with PHP Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">Send Bulk Email using PHPMailer with PHP Ajax</h3>
   <br />
   <div class="table-responsive">
    <table class="table table-bordered table-striped">
     <tr>
      <th>Customer Name</th>
      <th>Email</th>
      <th>Select</th>
      <th>Action</th>
     </tr>
     <?php
     $count = 0;
     foreach($result as $row)
     {
      $count++;
      echo '
      <tr>
       <td>'.$row["customer_name"].'</td>
       <td>'.$row["customer_email"].'</td>
       <td>
        <input type="checkbox" name="single_select" class="single_select" data-email="'.$row["customer_email"].'" data-name="'.$row["customer_name"].'" />
       </td>
       <td><button type="button" name="email_button" class="btn btn-info btn-xs email_button" id="'.$count.'" data-email="'.$row["customer_email"].'" data-name="'.$row["customer_name"].'" data-action="single">Send Single</button></td>
      </tr>
      ';
     }
     ?>
     <tr>
      <td colspan="3"></td>
      <td><button type="button" name="bulk_email" class="btn btn-info email_button" id="bulk_email" data-action="bulk">Send Bulk</button></td></td>
     </td>
    </table>
   </div>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 $('.email_button').click(function(){
  $(this).attr('disabled', 'disabled');
  var id = $(this).attr("id");
  var action = $(this).data("action");
  var email_data = [];
  if(action == 'single')
  {
   email_data.push({
    email: $(this).data("email"),
    name: $(this).data("name")
   });
  }
  else
  {
   $('.single_select').each(function(){
    if($(this). prop("checked") == true)
    {
     email_data.push({
      email: $(this).data("email"),
      name: $(this).data('name')
     });
    }
   });
  }
  
  $.ajax({
   url:"send_mail.php",
   method:"POST",
   data:{email_data:email_data},
   beforeSend:function(){
    $('#'+id).html('Sending...');
    $('#'+id).addClass('btn-danger');
   },
   success:function(data){
    if(data = 'ok')
    {
     $('#'+id).text('Success');
     $('#'+id).removeClass('btn-danger');
     $('#'+id).removeClass('btn-info');
     $('#'+id).addClass('btn-success');
    }
    else
    {
     $('#'+id).text(data);
    }
    $('#'+id).attr('disabled', false);
   }
   
  });
 });
});
</script>


send_mail.php



<?php
//send_mail.php

if(isset($_POST['email_data']))
{
 require 'class/class.phpmailer.php';
 $output = '';
 foreach($_POST['email_data'] as $row)
 {
  $mail = new PHPMailer;
  $mail->IsSMTP();        //Sets Mailer to send message using SMTP
  $mail->Host = 'smtpout.secureserver.net';  //Sets the SMTP hosts of your Email hosting, this for Godaddy
  $mail->Port = '80';        //Sets the default SMTP server port
  $mail->SMTPAuth = true;       //Sets SMTP authentication. Utilizes the Username and Password variables
  $mail->Username = 'xxxxxxxxxx';     //Sets SMTP username
  $mail->Password = 'xxxxxxxxxx';     //Sets SMTP password
  $mail->SMTPSecure = '';       //Sets connection prefix. Options are "", "ssl" or "tls"
  $mail->From = 'info@webslesson.com';   //Sets the From email address for the message
  $mail->FromName = 'Webslesson';     //Sets the From name of the message
  $mail->AddAddress($row["email"], $row["name"]); //Adds a "To" address
  $mail->WordWrap = 50;       //Sets word wrapping on the body of the message to a given number of characters
  $mail->IsHTML(true);       //Sets message type to HTML
  $mail->Subject = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit'; //Sets the Subject of the message
  //An HTML or plain text message body
  $mail->Body = '
  <p>Sed at odio sapien. Vivamus efficitur, nibh sit amet consequat suscipit, ante quam eleifend felis, mattis dignissim lectus ipsum eget lectus. Nullam aliquam tellus vitae nisi lobortis, in hendrerit metus facilisis. Donec iaculis viverra purus a efficitur. Maecenas dignissim finibus ultricies. Curabitur ultricies tempor mi ut malesuada. Morbi placerat neque blandit, volutpat felis et, tincidunt nisl.</p>
  <p>In imperdiet congue sollicitudin. Quisque finibus, ipsum eget sagittis pellentesque, eros leo tempor ante, interdum mollis tortor diam ut nisl. Vivamus odio mi, congue eu ipsum vulputate, consequat hendrerit sapien. Aenean mauris nibh, ultrices accumsan ultricies eget, ultrices ut dui. Donec bibendum lectus a nibh interdum, vel condimentum eros auctor.</p>
  <p>Quisque dignissim pharetra tortor, sit amet auctor enim euismod at. Sed vitae enim at augue convallis pellentesque. Donec rhoncus nisi et posuere fringilla. Phasellus elementum iaculis convallis. Curabitur laoreet, dui eget lacinia suscipit, quam erat vehicula nulla, non ultrices elit massa eu dolor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam vulputate mauris vel ultricies tempor.</p>
  <p>Mauris est leo, tincidunt sit amet lacinia eget, consequat convallis justo. Morbi sollicitudin purus arcu. Suspendisse pellentesque interdum enim non consectetur. Etiam eleifend pharetra ante a feugiat.</p>
  ';

  $mail->AltBody = '';

  $result = $mail->Send();      //Send an Email. Return true on success or false on error

  if($result["code"] == '400')
  {
   $output .= html_entity_decode($result['full_error']);
  }

 }
 if($output == '')
 {
  echo 'ok';
 }
 else
 {
  echo $output;
 }
}

?>

33 comments:

  1. The best canal and site about ajax/jquery *-*

    ReplyDelete
  2. thank you
    how did the phpmailer became class.phpmailer.php ?
    the sql file of the table could help

    ReplyDelete
  3. how to get a prompt if no mail id is selected to send bulk emails

    ReplyDelete
  4. can you help me it's not working am not getting any mail

    ReplyDelete
  5. i added my gmail to this code when i click on send single i am getting success but i am not receive any mails.kindly update me please

    ReplyDelete
    Replies
    1. Try it in server, localhost wont work.

      Delete
    2. try it online server, In localhost cant send email with PHP mailer

      Delete
    3. hello the online server is?? same question for me the system is success but i can not receive email

      Delete
  6. can i disable Email address in database after successfully sent an email please let me know is there any possibility

    Thanks in advance

    ReplyDelete
  7. How can i email individual row data from mysql to individual users?

    ReplyDelete
  8. can you provide a sort method with this script?

    ReplyDelete
  9. help with the script to send database data to the bulk email..that is if i add more columns to the database and i want to send some of those columns to respective emails

    ReplyDelete
  10. How about composing the message first (subject and body) then sending it to single/multiple recipients? Do you have a sample code for this?

    ReplyDelete
  11. please i having issues making the message dynamic... i added a textarea but its not getting my input

    ReplyDelete
  12. I want to write subject and message body myself.
    How can i make it ???

    ReplyDelete
  13. Sir I want add subject and message body from my side ??
    How can I do this ?

    ReplyDelete
  14. Its not working in live server...

    ReplyDelete
  15. How to import emails into the database

    ReplyDelete
  16. Hi, please I Ned assistance from this post. I saw this on YouTube 4days ago and decided to give it a trial, after watching the video, I downloaded it also the source code from this page and everything displayed as in this tutorial but after clicking on send button, I got success but no massage received in my inbox or spam box so I move it on online e server and did the same but no mail was received in my inbox. Please is there away out of this problem? Any help would be highly appreciated. Thanks.

    ReplyDelete
  17. I tried it on live server.
    It shows success message.
    But emails are not receiving.

    ReplyDelete
  18. It just allow 100 clicks on single sends.
    after 100 single send button its disabled.
    1-100 single send is working fine with no issue.

    ReplyDelete
  19. how many mails can send in same time ?

    ReplyDelete
  20. How can I use it to send emails for my website RSS feed.

    Regards,
    Theidioms.com

    ReplyDelete
  21. hello ! Thank your codes and i have a probleem
    look this noties Trying to access array offset on value of type bool in

    i got it
    how can i solve this probleem ?

    ReplyDelete
  22. Error in this part
    if($result ['Code'] == '440')
    {
    $output .= html_entity_decode($result['full_error']);
    }

    it say's you are trying to access boolean value

    ReplyDelete
  23. Will this work on live website?

    ReplyDelete
  24. thank the program is running. thanks

    ReplyDelete
  25. How can make it working for 5000 instead of 100??

    ReplyDelete