Demo Online
Download Code
- 5 years ago
- Zaid Bin Khalid
- 21501 Views
-
12
Many learners have the same question how can we send multiple emails using PHPMailer Class with email validation. In this example, I am going to tell you how you can validate email on user-end as well as a back-end, and send email to multiple recipients. Follow the tutorial step by step to accomplish the task.
We will use bootstrap for front-end design and PHP as a server-side language.
Step 1.
First we need to create a directory structure.
- Create a folder with a name send-emails in this folder create following.
- Create a folder name class.
- Download PHPMailer class and place into it class folder. [Download].
- Create a folder name ajax.
- In ajax folder create a file with the name action.ajax.php
- Download Bootstrap Lib [Download Link] or include using CDN.
- Create a file with extension .php and name index.php.
We use CDN to install bootstrap 4 and JQuery and other JQuery Plugins.
And we use Summernote WYSIWYG a text editor and Google Recaptcha V2
Step 2
Open index.php file in any IDE or in a notepad and past below snippet.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Validate Emails and send using PHPMailer and JQuery Ajax</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/summernote-bs4.min.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/summernote-bs4.min.js"></script>
</body>
</html>
In the above snippet, you can see we add CDN links into a <head> tag. After that, we design form use below code to create a form with email, subject, and text area field. Copy below code after the body tag.
<div class="container">
<div class="col-sm-12">
<div id="emailMsg"></div>
<form id="emailFrom" method="post" onsubmit="return false;">
<input type="hidden" name="sendEmail" value="ok" />
<div class="form-group">
<label>To:</label>
<input type="text" name="to" id="to" class="form-control-lg form-control" 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="staticEmail">Subject:</label>
<input class="form-control form-control-lg" id="subject" name="subject" placeholder="Enter your subject" type="text" required="required">
</div>
<div class="form-group">
<textarea name="mailEditor" id="txtEditor"></textarea>
</div>
<div class="form-group">
<button type="submit" name="submit" class="btn btn-primary">Send Email</button>
</div>
</form>
</div>
</div>
Now we need to handle form submission and validate emails on the user end. For that use below script. Past this script just before <div class=”container”>
<script>
$(document).ready(function(e){
$("#emailFrom").on("submit",function(){
$("html, body").animate({scrollTop: 0}, 1000);
email = $("#to").val();
if(email!=""){
totalEmail = email.split(',');
countEmail = totalEmail.length;
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"><i class="fa fa-fw fa-exclamation-triangle"></i> Email(s) typo error ('+noEmails+') <strong>Please type correct email(s)!</strong></div>');
flag = 1;
}
}
if(flag==1){
$("#eMsg").html('<small><em class="text text-danger"> <strong>Example:</strong> example<strong>@</strong>gmail<strong>.com</strong></i></small>');
return false;
}
$("#emailMsg").html('<div class="overlay"><i class="fa fa-fw fa-spin fa-spinner"></i> Please wait...!</div>');
$.ajax({
type:'POST',
url:'ajax/action.ajax.php',
data:$("#emailFrom").serialize(),
success: function(data){
a = data.split('|***|');
if(a[1]==1){
$("#emailMsg").html(a[0]);
$("#to,#subject").val('');
}else{
$("#emailMsg").html(a[0]);
}
}
});
}else{
$("#emailMsg").html('<div class="alert alert-danger"><i class="fa fa-fw fa-exclamation-triangle"></i> Enter email first <strong>Please type correct email(s)!</strong></div>');
return false;
}
});
$('textarea').summernote({
height: 300, //set editable area's height
});
});
function emailValidate(email) {
var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
</script>
Highlighted code form 24-38 show ajax request that we use to send an email. And the highlighted code form 45-47 show summernote initialization. Now open file action.ajax.php past below code in it.
<?php
include_once('../class/PHPMailer.php');
if(isset($_REQUEST['sendEmail']) and $_REQUEST['sendEmail']!=""){
$to = explode(',',$_POST['to']);
$message = str_replace("\\","", $_POST['mailEditor']);
$message .= "<br><br>Powered By Learn Code Web <br><br><img src='https://learncodeweb.com/wp-content/uploads/2019/01/logo.png' border='0'><br><br>web : <a href='https://learncodeweb.com' target='_blank'>Learn Code Web</a>";
$mail = new PHPMailer();
$mail->CharSet="UTF-8"; // <-- Put right encoding here
define("FROM_EMAIL","[email protected]");
define("FROM_EMAIL_NAME",'Learn Code Web');
$mail->Subject = $_POST['subject'];
$mail->SetFrom(FROM_EMAIL, FROM_EMAIL_NAME);
$mail->AddAttachment('../uploads/logo.png');
$mail->MsgHTML($message);
foreach($to as $hoemail){
$mail->clearAddresses();
$mail->ClearAllRecipients();
$mail->AddAddress($hoemail);
if($mail->Send())
$ms = true;
else
$ms = false;
$noemail[] = $hoemail;
}
if($ms){
echo '<div class="alert alert-success"><i class="fa fa-fw fa-thumbs-up"></i> Email sent successfylly</div>|***|1';
exit;
}else{
echo '<div class="alert alert-danger"><i class="fa fa-fw fa-exclamation-triangle"></i> Email not sent to '.implode(", ",$noemail).' <strong>Please try again or type correct email!</strong></div>|***|0';
exit;
}
}
?>
Enter your email and check the functionality. You can enter multiple emails to check the validation of the script.
Demo Online
Download Code
- 5 years ago
- Zaid Bin Khalid
- 21501 Views
-
12