AdSense

Send multiple email at once in Gmail using PHP jQuery AJAX How to configure SMTP server to Send Email using PHP ? gmail smtp settings send email using php php code to send email from contact form phpmailer php


Hello Guys, In this post we have a simple application we can use to send multiple emails to users with one click. Here we are using Jquery with Ajax so that we can send emails without reload the web page. When we press the Send mail button, the email from the input field data attribute is captured with jquery. After collecting data, it is sent to an ajax request and passed to and into the PHP script via an ajax request. If we use the PHPMailer class with the required SMTP configuration, it will be a multiple email sent. After all emails have been successfully sent, the data will be sent to Ajax upon request and displayed on the website. This way we can use Ajax with Jquery to send bulk emails using PHP with PHPMailer Library


We use SMTP to send bulk emails because SMTP is our best way to send email from localhost or an online server. How to configure SMTP server to Send Email using PHP ? which we can use to send emails via SMTP and provide the necessary credentials. If you have a web hosting email account, your hosting company will provide you with SMTP credentials such as username, password, outgoing and incoming server addresses, and port number. You can use this information to configure these details in the PHPMailer class and then send an email from your script.


See also

  1. How to Send Bulk Emails in PHP using PHPMailer with Ajax JQuery
  2. How to configure SMTP server to Send Email using PHP ?
  3. Contact form send attachment using jquery ajax in PHP
  4. Contact form with validation in PHP mailer jquery Ajax script, (PHP code to send email from contact form)

Output

Send multiple email at once in Gmail using PHP jQuery AJAX

There are some step to follow to send multiple email 

Steps

  1. Download PHPMailer library from GitHub and include our project folder.
  2. Create HTML page for Send multiple emails 
  3. Create action page for Send email in PHP

Create HTML Page for Send multiple emails

index.php
<!Doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>How to Send multiple email at once in Gmail using PHP jQuery AJAX</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>
<body>
<style type="text/css">
    .container{ margin-top:50px; }
    h2{ text-align:center;}
    .btn-primary{ float: right;}
</style>
<div class="container">
<h2><b>Send multiple email at once in Gmail using PHP jQuery AJAX</b></h2><br>
   <div class="row">
    <div class="col-md-2"></div>
      <div class="col-md-8">
         <div id="emailMsg"></div>
         <form id="emailFrom" method="post" onsubmit="return false;">
            <div class="form-group">
               <label for="to">To:</label>
               <input type="text" class="form-control" id="toEmail" name="toEmail" placeholder="More than one email, Please seperate with comma (,)" >
               <div class="text-danger"><small>* More than one email, Please seperate with comma (,)</small></div>
            </div>
            <div class="form-group">
               <label for="subject">Subject:</label>
               <input type="text" class="form-control" id="subject" name="subject" placeholder="Subject">
            </div>
            <div class="form-group">
               <label for="message">Message:</label>
               <textarea rows="5" class="form-control" name="message" id="message" placeholder="Message"></textarea>
            </div>
            <div class="form-group">
               <button type="submit" name="submit" class="btn btn-primary">Send Email</button>
            </div>
         </form>
      </div>
   </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</body>
</html>

JQuery AJAX Code

<script type="text/javascript">
   $(document).ready(function(){
      $("#emailFrom").on("submit", function(){
         var email = $("#toEmail").val();
         if (email != "") {
            var totalEmail = email.split(',');
            var countEmail = totalEmail.lenght;
            flag = 0;
            noEmails = "";
            for(i=0;i<countEmail;i++){
              if(emailValidate(totalEmail[i])===false){
                var elements = [totalEmail[i]];
                var noEmails = elements.join(',');
                $("#emailMsg").html('<div class="alert alert-danger">Email(s) typo error ('+noEmails+') <strong>Please type correct email(s)!</strong></div>');     
                flag = 1;
              }
            }
            if(flag==1){
              $("#emailMsg").html('<small class="text text-danger"><strong>Example:</strong>example@gmail.com </small>');
              return false;
            }
            $("#emailMsg").html('<div class="alert alert-danger">Please wait...!</div>');
            $.ajax({
              type : "POST",
              url  : "action.php",
              data : $("#emailFrom").serialize(),
              success:function(data){
                a = data.split('|***|');
                if(a[1]==1){
                    $("#emailMsg").html(a[0]);
                    $("#emailFrom").trigger('reset');
                }else{
                    $("#emailMsg").html(a[0]);
                }
              }
          });
         }else{
            $("#emailMsg").html('<div class="alert alert-danger">Enter email first Please type correct email(s)!</div>');
            return false;
         }
      });
   });

   function emailValidate(email) {
      var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
      return regex.test(email);
   }

</script>

Create action page for Send email in PHP

action.php
<?php

if(isset($_POST['toEmail']) && $_POST['toEmail']!=""){

	require_once ('PHPMailer/PHPMailerAutoload.php');

        $toEmail       = explode(',',$_POST['toEmail']);
        $message  = str_replace("\\","", $_POST['message']);
        $subject  = $_POST['subject'];

	$message .= "<br>Powered By Webs Codex <br><br>Web: <a href='https://www.webscodex.com/' target='_blank'>Webs Codex</a>";

        $mail = new PHPMailer(true);

	$mail->SMTPDebug = 3;                                 // Enable verbose debug output
	$mail->CharSet="UTF-8";                               // Put right encoding here  
	$mail->isSMTP();                                      // Set mailer to use SMTP
	$mail->Host = 'smtp.gmail.com';  					  // Specify main and backup SMTP servers
	$mail->SMTPAuth = true;                               // Enable SMTP authentication
	$mail->Username = 'YourEmailAdress';                  // SMTP username
	$mail->Password = 'YourEmailPassword';                // SMTP password
	$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
	$mail->Port = 587;                                    // TCP port to connect to
	$mail->isHTML(true); 								  // Set email format to HTML

        $mail->SMTPOptions = array(
            'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
            )
        );

	foreach($toEmail as $email){
        
        $mail->setFrom($email, 'Webs Codex');
        $mail->addAddress($email, 'Your Name');             // Add a recipient
        $mail->addReplyTo($email, 'Webs Codex');
        
        $mail->Subject = $subject;
        $mail->Body    = $message;    

        if($mail->send()){
            $esmessage = true;
        }else{
    		$esmessage = false;
        	$noemail[] = $email;			
    	}
    }

    if($esmessage){
        echo'<div class="alert alert-success alert-dismissible">
                <button type="button" class="close" data-dismiss="alert">&times;</button>
                Email sent successfully
            </div>';
        exit;
    }else{
        echo'<div class="alert alert-danger alert-dismissible">
                <button type="button" class="close" data-dismiss="alert">&times;</button>
                Email not sent to '.implode(", ",$noemail).' <strong>Please try again or type correct email!</strong>
            </div>';
        exit;           
    }
}


?>


You can always support by sharing on social media or recommending my blog to your friends and colleagues.   
If you have any suggestions / problems about this tutorial, please comment on the  form below.😊

2 Comments

  1. If I add 2 emails the mail will come twice likewise if I add 200 mails I'll come 200 times in one mails

    ReplyDelete
    Replies
    1. you can learn this method also

      https://www.webscodex.com/2020/08/how-to-send-bulk-email-in-php-using.html

      Delete

Post a Comment

Previous Post Next Post