Send Email using PHP and AJAX

Hello everyone, Today in this blog we are going to learn how we can send email using PHP. Keep in mind when sending e-mails through PHP is a relatively simple task, but set all the configuration and authentication and to make sure you are sending correctly is where it becomes challenging.

To actually send emails (in a relatively easy manner), an important part of the code you might want to focus on is what SMTP server you are using, for a quick setup you could easily use gmails SMTP with your Gmail account credentials and utilize a mail library such as PHPMailer.

Let’s start with create a form page and when you submit your page then back end you have to write you code for send your email I demonstrate here some step, where the edit is required replace it with your own post input value.

Send mail using PHP is a very essential part of a web application for doing this in PHP we have to do something right three-step which I discuss here. For sending an email in PHP we use phpmailer library and SMTP server of Gmail smtp.gmail.com believe me it very easy if you follow all these steps

  • download phpmailer library and install it
  • write code for send email
  • fix an error that occurs when we send an email

You May Also Like:

First of all, we create an HTML file

The HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Email Form</title>
    <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css'>
    <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css'>
    <link rel='stylesheet' href='style.css'>
</head>
<body>
  <!-- Image loader -->
    <div id="loading" style="display: none">
      <div id="loading-center">
        <div id="loading-center-absolute">
          <div class="object" id="object_one"></div>
          <div class="object" id="object_two"></div>
          <div class="object" id="object_three"></div>
        </div>
      </div>
    </div>
    <!-- Image loader -->
    <div class="container">
        <div class="container-inner">
          <h2 class="text-center">Send E-Mail</h2>
            <form class="form-email" method="POST">
                <div class="form-group">
                    <div class="input-group">
                        <input type="email" name="toemail" id="toemail" class="form-control" placeholder="To">
                        <div class="input-group-btn">
                            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown"><i class="fa fa-cog"></i> <span class="caret"></span></button>
                            <ul class="dropdown-menu pull-right">
                                <li><a data-toggle="address" data-target="#cc" href="#">Add Cc</a></li>
                                <li><a data-toggle="address" data-target="#bcc" href="#">Add Bcc</a></li>
                            </ul>
                        </div>
                    </div>
                    <small class="help-block text-muted">You may add multiple email addresses and separate them with a comma.</small>
                </div>
                <div class="form-group" id="cc">
                    <input type="text" class="form-control" placeholder="Cc">
                    <button data-toggle="remove" class="remove">&times;</button>
                </div>
                <div class="form-group" id="bcc">
                    <input type="text" class="form-control" placeholder="Bcc">
                    <button data-toggle="remove" class="remove">&times;</button>
                </div>
                <div class="form-group">
                    <input type="text" name="subject" id="subject" class="form-control" placeholder="Subject">
                </div>
                <ul class="nav nav-tabs">
                    <li class="active"><a data-toggle="tab" href="#write">Write</a></li>
                </ul>
                <div class="tab-content">
                    <div class="tab-pane active" id="write">
                        <textarea class="form-control" name="message" id="message" rows="10"></textarea>
                    </div>
                </div>
                <div class="text-right">
                    <button class="btn btn-success" type="button" id="sendemail">
                    <i class="fa fa-send"></i> &nbsp; Send
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script src='https://code.jquery.com/jquery-2.2.4.min.js'></script>
    <script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js'></script>
    <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
    <script src='main.js'></script>
</body>

</html>

The CSS

html, body {
     height: 100%;
     background-color: #fcfcfc;
}
 body > .container, body > .container > .container-inner {
     height: 100%;
     width: 600px;
}
 body > .container {
     display: table;
     padding-top: 20px;
}
 body > .container > .container-inner {
     display: table-cell;
}
 .form-email {
     padding: 15px;
     border: 1px solid #cccccc;
     border-radius: 4px;
     box-shadow: 0 4px 6px -2px #eeeeee;
}
 .form-email .nav-tabs {
     margin-left: -15px;
     margin-right: -15px;
     padding-left: 15px;
     padding-right: 15px;
}
 .form-email .nav-tabs > .pull-right {
     margin-right: -15px;
}
 .form-email .nav-tabs > .pull-right > a {
     color: #555555;
     font-weight: bold;
}
 .form-email .nav-tabs > .pull-right > a:hover {
     color: #428bca;
     border-color: transparent;
     background-color: transparent;
}
 .form-email .tab-content {
     padding-top: 20px;
     padding-bottom: 15px;
}
 .form-email .form-group {
     position: relative;
}
 .form-email .form-group > .remove {
     -webkit-transition: opacity 0.2s ease;
     -moz-transition: opacity 0.2s ease;
     -o-transition: opacity 0.2s ease;
     transition: opacity 0.2s ease;
     position: absolute;
     top: 1px;
     right: 1px;
     display: inline-block;
     height: 36px;
     margin-bottom: 0;
     padding-left: px;
     padding-right: 10px;
     font-weight: bold;
     font-size: 18px;
     text-align: center;
     vertical-align: middle;
     cursor: pointer;
     border: 0 none;
     border-top-right-radius: 4px;
     border-bottom-right-radius: 4px;
     background-color: rgba(255, 255, 255, 0.95);
     opacity: 0.5;
}
 .form-email .form-group > .remove:hover {
     opacity: 1;
}
 .form-email input[type="text"].form-control, .form-email input[type="email"].form-control {
     height: 38px;
}
 .form-email .input-group {
     width: 100%;
}
 .form-email .btn {
     height: 38px;
}
 .form-email textarea.form-control {
     resize: vertical;
     border-bottom-color: transparent;
     background-color: #fbfbfb;
     border-bottom-left-radius: 0;
     border-bottom-right-radius: 0;
}
 .form-email textarea.form-control:focus {
     background-color: #ffffff;
}
 #bcc, #cc {
     -webkit-transition: all 0.3s ease 0.5s;
     -moz-transition: all 0.3s ease 0.5s;
     -o-transition: all 0.3s ease 0.5s;
     transition: all 0.3s ease 0.5s;
     display: none;
     opacity: 0;
}
 #bcc.active, #cc.active {
     -webkit-transition: all 0.2s ease 0s;
     -moz-transition: all 0.2s ease 0s;
     -o-transition: all 0.2s ease 0s;
     transition: all 0.2s ease 0s;
     display: block;
     opacity: 1;
}
/*Loader Css*/
 #loading{
     background-color: rgba(55,55,55,0.7);
     height: 100%;
     width: 100%;
     position: fixed;
     z-index: 99999;
     margin-top: 0px;
     top: 0px;
}
 #loading-center{
     width: 100%;
     height: 100%;
     position: relative;
}
 #loading-center-absolute {
     position: absolute;
     left: 50%;
     top: 50%;
     height: 150px;
     width: 150px;
     margin-top: -75px;
     margin-left: -75px;
}
 .object{
     width: 20px;
     height: 20px;
     background-color: #FFF;
     float: left;
     margin-right: 20px;
     margin-top: 65px;
     -moz-border-radius: 50% 50% 50% 50%;
     -webkit-border-radius: 50% 50% 50% 50%;
     border-radius: 50% 50% 50% 50%;
}
 #object_one {
     -webkit-animation: object_one 1.5s infinite;
     animation: object_one 1.5s infinite;
}
 #object_two {
     -webkit-animation: object_two 1.5s infinite;
     animation: object_two 1.5s infinite;
     -webkit-animation-delay: 0.25s;
     animation-delay: 0.25s;
}
 #object_three {
     -webkit-animation: object_three 1.5s infinite;
     animation: object_three 1.5s infinite;
     -webkit-animation-delay: 0.5s;
     animation-delay: 0.5s;
}
 @-webkit-keyframes object_one {
     75% {
         -webkit-transform: scale(0);
    }
}
 @keyframes object_one {
     75% {
         transform: scale(0);
         -webkit-transform: scale(0);
    }
}
 @-webkit-keyframes object_two {
     75% {
         -webkit-transform: scale(0);
    }
}
 @keyframes object_two {
     75% {
         transform: scale(0);
         -webkit-transform: scale(0);
    }
}
 @-webkit-keyframes object_three {
     75% {
         -webkit-transform: scale(0);
    }
}
 @keyframes object_three {
     75% {
         transform: scale(0);
         -webkit-transform: scale(0);
    }
}

The JavaScript

 +function ($) {'use strict';
      var togglr = '[data-toggle=address]',
      remove = '[data-toggle="remove"]';
    
      $(togglr).on('click', function (e) {
        var target = $(this).data('target');
    
        $(target).toggleClass('active');
    
        e.preventDefault();
      });
    
      $(remove).on('click', function (e) {
        var parent = $(this).parent();
    
        if ($(parent).hasClass('active')) {
          $(parent).removeClass('active');
          $(parent, 'input').val('');
        }
    
        e.preventDefault();
      });
    }(window.jQuery);

//validating user input
    function ValidateEmailForm(){
        if( document.getElementById('toemail').value == "")
        {
          swal("Error","Please Enter To Email ID", {icon: "error",});
          document.getElementById('toemail').focus() ;
          return false;
        }
        if( document.getElementById('subject').value == "" )
        {
          swal("Error","Please Enter Your Subject", {icon: "error",});
          document.getElementById('subject').focus() ;
          return false;
        }
        if( document.getElementById('message').value == "" )
        {
          swal("Error","Please Enter Your Message", {icon: "error",});
          document.getElementById('message').focus() ;
          return false;
        }
        return true;
      }
  //onclick event to submit a form
      $('#sendemail').on("click", function(){
          var validateform = ValidateEmailForm();
          if(validateform === true){
            var toemail = $('#toemail').val();
            var subject = $('#subject').val();
            var message = $('#message').val();
            $.ajax({  
              url:"sendEmail.php",  
              method:"post",
              data:{toemail:toemail,subject:subject,message:message},
              beforeSend: function(){
                // Show image container
                $("#loading").show();
              },
              success:function(result){
                console.log(result);
                if(result.code==1){
                  swal("Success",result.message, {icon: "success",});
                  window.setTimeout(function(){
                    window.location.href = "email.php";
                  }, 1000);
                }
                else{
                  swal("Error",result.message, {icon: "error",});
                }
              },
              complete:function(html){
                // Hide image container
                $("#loading").hide();
              }
            });
          }
          return false;
      });

The PHP Script

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
//Load Composer's autoloader
require ('mail/vendor/autoload.php');
header('Content-Type: application/json');

	if (!empty($_POST['toemail']) && !empty($_POST['subject']) && !empty($_POST['message'])) {
	    try{
		    $result = array();
		    $toemail=$_POST['toemail'];
		    $subject=$_POST['subject'];
		    $messages=$_POST['message'];
		    $mail = new PHPMailer(true);
		    $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 = 'username';          // SMTP username
			$mail->Password = 'password';                        // SMTP password
			$mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
			$mail->Port = 465;    

			//Recipients
			$mail->setFrom('sentfromemail', 'Eamil Heading');
			$mail->addAddress($toemail);     // Add a recipient

			//Content
			$mail->isHTML(true);                                 	 // Set email format to HTML
			$mail->Subject = $subject;
			$mail->Body    = $messages;
			if($mail->send()){
				$result['message'] = "Email Send Successfully";
				$result['code']=1;
			}
			else{
				$result['message'] = "Message could not be sent. Mailer Error";
				$result['code']=0;
			}
		}
		catch(PDOException $e){
			$result['message'] = "There is some problem" . $e->getMessage();
		    $result['code']=0;
		}
		echo json_encode($result);
	}

Output:

email-output

View Demo Download Source Code

Thank you for reading this blog, share this blog as much as possible and also show it to your friends. If you have any questions, feel free to comment.

0 Comments

No Comment.