Geeks Trick
Send Email Using PHP and JavaScript

Send Email Using PHP and JavaScript

In this tutorial we will see how to Send Email Using PHP and JavaScript through the html forms.



Email Form

Let’s start with building a form using Bootstrap classes. As you can create your own custom design for your form, but all you need to do is to declare the id for every particular input.
It takes the value from the form and stores in the variables, which will be declared in the javascript file.

So first declare the form tag.

<!-- Set id for email form -->
<form name="sendMail" id="sendMailForm">

</form>

And now for taking the value from the user, we will create the input in the form using Bootstrap classes, also we will create the notification after the message is sent successfully or if any error occured.

<form name="sendMail" id="sendMailForm">
		<div class="form-group user-name">
			<label for="name" class="sr-only">Name</label>
			<!-- "id" for taking name -->
			<input type="text" class="form-control" required="" id="name" placeholder="First Name">
		</div>
		<div class="form-group user-email">
			<label for="email" class="sr-only">Email</label>
			<!-- "id" for taking email -->
			<input type="email" class="form-control" required="" id="email" placeholder="Email Address">
		</div>
		<div class="form-group user-phone">
			<label for="contactNumber" class="sr-only">Contact Number</label>
			<!-- "id" for taking contact number -->
			<input type="text" class="form-control" required="" id="contactNumber" placeholder="Phone">
		</div>
		<div class="form-group user-message">
			<label for="message" class="sr-only">Message</label>
			<!-- "id" for taking message -->
			<textarea class="form-control" required="" id="message" placeholder="Write Message"></textarea>
		</div>
	<!-- Notifications for 'error' Or 'successfully'-->
		<div class="col-md-12 mailResponse" style="display:none;">
			<div class="alert alert-dismissible" role="alert">
				<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
				<p class="mailResponseText"></p>
			</div>
		</div>
	<!-- submit button -->
	<button type="submit" class="btn btn-primary">Send Message <i class="fa fa-paper-plane"></i></button>
</form>

Javascript For Email

The script file store the values from the form into the variables. We will also using JQuery for toggle the notification.


// #sendMailForm takes the data from the form with given ID
$( '#sendMailForm' ).submit(function ( e ) {
    var data = {
        'name': $('#name').val(),
        'email': $('#email').val(),
        'contact': $('#contactNumber').val(),
        'message' : $('#message').val()
    };
    // POST data to the php file
    $.ajax({ 
        url: 'mail.php', 
        data: data,
        type: 'POST',
        success: function (data) {
			// For Notification
            document.getElementById("sendMailForm").reset();
            var $alertDiv = $(".mailResponse");
            $alertDiv.show();
            $alertDiv.find('.alert').removeClass('alert-danger alert-success');
            $alertDiv.find('.mailResponseText').text("");
            if(data.error){
                $alertDiv.find('.alert').addClass('alert-danger');
                $alertDiv.find('.mailResponseText').text(data.message);
            }else{
                $alertDiv.find('.alert').addClass('alert-success');
                $alertDiv.find('.mailResponseText').text(data.message);
            }
        }
    });
    e.preventDefault();
});

PHP Email Transfer

In the PHP code we will set where the mail to be transfer from the website by giving particular email id, and also we will set the data to send in email i.e. the email details containing the name, contact number, email address and the message.
Where the data send in header are in JSON format.

<?php
   // data sent in header are in JSON format
   header('Content-Type: application/json');
   // takes the value from variables and Post the data
   $name = $_POST['name'];
   $email = $_POST['email'];
   $contact = $_POST['contact'];
   $postmessage = $_POST['message'];  
   $to = "example@email.com";
   $subject = "Contact Us";
   // Email Template
   $message = "<b>Name : </b>". $name ."<br>";
   $message .= "<b>Contact Number : </b>".$contact."<br>";
   $message .= "<b>Email Address : </b>".$email."<br>";
   $message .= "<b>Message : </b>".$postmessage."<br>";

   $header = "From:"+$email+" \r\n";
   $header .= "MIME-Version: 1.0\r\n";
   $header .= "Content-type: text/html\r\n";
   $retval = mail ($to,$subject,$message,$header);
   // message Notification
   if( $retval == true ) {
      echo json_encode(array(
         'success'=> true,
         'message' => 'Message sent successfully'
      ));
   }else {
      echo json_encode(array(
         'error'=> true,
         'message' => 'Error sending message'
      ));
   }
?>


NOTE : The working of sending Email will not work on localhost. Its only applicable to run on hosting server.

Rehmaanali

Hi This Is Rehmaanali.
Blogging Is Just A Hobby.
Graduate In Bsc Computer Science

Add comment

Author

Rehmaanali

Hi This Is Rehmaanali.
Blogging Is Just A Hobby.
Graduate In Bsc Computer Science

Subscribe To Our Newsletter

Join our mailing list to receive the latest Articles news and updates from our team. 

You have Successfully Subscribed!