In this tutorial we are going to see how to send an E-Mail with attachment using jQuery, Ajax and PHP without refreshing a page.
Please check my latest Video tutorial on: Send Email with Attachment Using PHP, jQuery, PHPMailer & Ajax from Scratch to Advanced
Video Tutorials on Youtube: Send Email with Attachment Using PHP, Ajax, jQuery & PHPMailer
Step 1:
Create index.php file and add the following html code to design html email form.
<div class="title"> <h1>Mail Demo Page</h1> </div> <div class="mail"> <div id='message1'> <img id='close' src='images/close.png'/> <h2>Mail Sent Successfully!</h2> <p>We will be in touch soon.</p> <img id='checkmark' src='images/check.png'/> </div> <form action='mail.php' method="post" id='mailForm' enctype='multipart/form-data'> <table> <tr> <td class="label"> Name : </td> <td><input type="text" id="name" name="name" class="form-input" placeholder='User Name'/></td> <td class="status"></td> </tr> <tr> <td class="label"> E-mail : </td> <td><input type="email" id="email" name="email" class="form-input" placeholder='E-Mail'/></td> <td class="status"></td> </tr> <tr> <td class="label"> From E-mail : </td> <td><input type="email" id="femail" name="femail" class="form-input" placeholder='From E-Mail'/></td> <td class="status"></td> </tr> <tr> <td class="label"> Phone : </td> <td><input type="tel" id="phone" name="phone" class="form-input" placeholder='Phone'/></td> <td class="status"></td> </tr> <tr> <td class="label"> Image : </td> <td><input type="file" id="image" name="image" class="form-input" placeholder='Image' accept="image/*"></td> <td class="status"></td> </tr> <tr> <td class="label"> Message : </td> <td><textarea cols="27" rows="5" id="message" name="message" placeholder='Message'></textarea></td> <td class="status"></td> </tr> <tr> <td colspan="2"> <input type="submit" value="Send Mail!" id='submit_btn' name="submit_btn" class="submit_btn"/></td> </tr> </table> </form> </div>
Step 2:
Create style.css file and add the following css code to add styling to your html form.
* {
background-color: #16a085;
margin: 0;
padding: 0;
}
@font-face{
font-family: Lobster;
src: url('Lobster.otf');
}
table{
color: #fff;
font-size: 20px;
}
.error_msg{
color: red;
}
td{
padding: 20px 0 0 0;
}
textarea{
border-radius: 5px;
color: #fff;
font-size : 17px;
font-family: Verdana;
}
textarea:focus{
color: #FF9900;
border: 2px solid green;
}
.mail{
width: 500px;
margin:0 auto;
}
.label{
text-align: right;
padding-right: 20px;
}
#image{
height: 30px;
}
.title{
font-family: Lobster;
text-align: center;
font-size: 35px;
color: #FFf;
margin: 50px 0 10px 0;
text-decoration:underline;
}
.form-input{
width: 275px;
height: 40px;
border-radius: 5px;
color: #999;
font-size : 17px;
background: #fff;
border: 2px solid #fff;
}
.form-input:focus{
color: #3D991F;
border: 2px solid green;
}
.submit_btn:hover{
background: green;
border: 2px solid green;
color: #fff;
}
.submit_btn{
margin-left: 140px;
width: 280px;
height: 45px;
border-radius: 5px;
color: #fff;
background-color: #EE872A;
font: bold 15px Verdana;
margin-bottom: 100px;
border: 2px solid #EE872A;
}
#message{
background: #fff;
color: #999;
border: 2px solid #fff;
}
em.error {
background:url("unchecked.gif") no-repeat 0px 0px;
padding-left: 16px;
color: #ff0000;
font-weight: bold;
}
em.success {
background:url("checked.gif") no-repeat 0px 0px;
padding-left: 16px;
color: #33ff55 ;
}
form.cmxform label.error {
margin-left: auto;
width: 250px;
color: red;
}
#warning { display: none; }
.status{
width : 250px;
position: absolute;
}
#message1{
display:none;
margin-left: 50px;
margin-top: 100px;
color: #fff;
width: 400px;
height: 100px;
border: 2px solid #fff;
border-radius: 10px;
position: relative;
}
#message1 h2, #message1 p{
text-align: center;
}
#message1 #checkmark{
margin-left: 170px;
}
#close{
position: absolute;
right: -8px;
top: -10px;
}
.hide{
display: none;
}
.preview{
width: 400px;
margin: 20px 0 50px 430px;
border: 10px dotted orange;
}
now we had almost completede designing part of the mail form.
Step 3:
Add following jQuery library in your index.php file.
<script src="js/jquery-1.9.1.min.js"></script> <script src="js/jquery.validate.min.js"></script> <script src="http://malsup.github.com/jquery.form.js"></script>
Step 4:
I used jQuery form plugin .ajaxForm() method to send to a form data’s to mail.php file.
here is syntax.
$('form').ajaxForm({
beforeSubmit: function() {
// validation script goes here
},
success: function(msg) {
// Success message goes here
},
complete: function(xhr) {
// some logic script goes here
}
});
Following script checks form is valid or not, in the beforeSubmit callback function
var flag= $('#mailForm').valid();
if(!flag){
return false;
}
if form is not valid then it won’t allows the form to submit.
Following script hides the form and shows success message after sucessful form submission.
$("#mailForm").addClass("hide");
$("#message1").show();
Following click event hides the success message, shows the form the form as well clears user entered information in the form.
$('#close').click(function(){
$('#message1').hide();
$("#mailForm").removeClass("hide");
$('input[type=text],input[type=email],textarea,input[type=tel],input[type=file]').val('');
location.reload();
});
Here is full jQuerey script
<script>
(function() {
$('form').ajaxForm({
beforeSubmit: function() {
//return $('#mailForm').validate().form();
$("#mailForm").validate({
rules: {
name: {
required: true,
minlength : 3
},
email:{
required: true,
email: true
},
phone: {
required : true,
number:true,
minlength : 10,
maxlength : 11
},
image: "required",
message: "required",
femail:{
required: true,
email: true
}
},
messages: {
name: {
required:"Please enter your name",
minlength: "Please enter a valid name"
},
email:{
required: "Please enter your email",
minlength: "Please enter a valid email address",
},
phone: {
required: "Please enter your phone number",
minlength: "Please enter your valid phone number",
maxlength: "Please enter your valid phone number"
},
image: "Please Choose your image",
message: "Please enter your message",
femail: {
required: "Please enter your email",
minlength: "Please enter a valid email address",
}
},
debug: true,
errorElement: "em",
errorContainer: $("#warning, #summary"),
errorPlacement: function(error, element) {
error.appendTo( element.parent("td").next("td") );
},
success: function(label) {
label.text("ok!").addClass("success");
}
});
var flag= $('#mailForm').valid();
if(!flag){
return false;
}
},
success: function(msg) {
alert(msg);
//$("#mailForm").addClass("hide");
//$("#message1").show();
},
complete: function(xhr) {
$("#mailForm").addClass("hide");
$("#message1").show();
$('#status').html(xhr.responseText);
}
});
$('#close').click(function(){
$('#message1').hide();
$("#mailForm").removeClass("hide");
$('input[type=text],input[type=email],textarea,input[type=tel],input[type=file]').val('');
location.reload();
});
})();
</script>
Step 5:
Now just follow php part coding. I am using php mail plugin to send an email with attachment.
Create mail.php file and add the following php file (class.phpmailer.php).
require 'class.phpmailer.php';
Step 6:
Now add to email ID.
$to = "Your email ID"; $mail->AddAddress($to);
Step 7:
Now get from email id and name of the user.
$mail->From = $_POST['femail']; $mail->FromName = $_POST['name'];
Step 8:
Now add subject of the mail.
$mail->Subject = "Test Email using PHP";
Step 9:
Now get message from the html form.
$body = "<table>
<tr>
<th colspan='2'>This Sample Mail</th>
</tr>
<tr>
<td>Name :</td>
<td>".$_POST['name']."</td>
</tr>
<tr>
<td>E-mail : </td>
<td>".$_POST['email']."</td>
</tr>
<tr>
<td>Phone : </td>
<td>".$_POST['phone']."</td>
</tr>
<tr>
<td>Message : </td>
<td>".$_POST['message']."</td>
</tr>
<table>";
$body = preg_replace('/\\\\/','', $body); //Strip backslashes
$mail->MsgHTML($body);
Step 10:
Finally get the attachment and send it.
$mail->AddAttachment($_FILES['image']['tmp_name'], $_FILES['image']['name']); $mail->IsHTML(true); // send as HTML $mail->Send(); echo 'Message has been sent.';
Here is the full php source code.
<?php
/**
* Simple example script using PHPMailer with exceptions enabled
* @package phpmailer
* @version $Id$
*/
require 'class.phpmailer.php';
try {
$mail = new PHPMailer(true); //New instance, with exceptions enabled
$to = $_POST['email'];
$mail->AddAddress($to);
$mail->From = $_POST['femail'];
$mail->FromName = $_POST['name'];
$mail->Subject = "Test Email using PHP";
$body = "<table>
<tr>
<th colspan='2'>This Sample Mail</th>
</tr>
<tr>
<td style='font-weight:bold'>Name :</td>
<td>".$_POST['name']."</td>
</tr>
<tr>
<td style='font-weight:bold'>E-mail : </td>
<td>".$_POST['email']."</td>
</tr>
<tr>
<td style='font-weight:bold'>Phone : </td>
<td>".$_POST['phone']."</td>
</tr>
<tr>
<td style='font-weight:bold'>Message : </td>
<td>".$_POST['message']."</td>
</tr>
<table>";
$body = preg_replace('/\\\\/','', $body); //Strip backslashes
$mail->MsgHTML($body);
$mail->IsSMTP(); // tell the class to use SMTP
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Port = 25; // set the SMTP server port
//$mail->Host = "mail.yourdomain.com"; // SMTP server
//$mail->Username = "name@domain.com"; // SMTP server username
//$mail->Password = "password"; // SMTP server password
$mail->IsSendmail(); // tell the class to use Sendmail
$mail->AddReplyTo("admin@smarttutorials.net");
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->WordWrap = 80; // set word wrap
$mail->AddAttachment($_FILES['image']['tmp_name'],
$_FILES['image']['name']);
$mail->IsHTML(true); // send as HTML
$mail->Send();
echo 'Message has been sent.';
} catch (phpmailerException $e) {
echo $e->errorMessage();
}
?>
You can also refer my another cool tutorial on PHP Script to Send Email with Attachment.
