Email send Using Angularjs and PHP

In the following example you learn how to Email sending with AngularJS and PHP

<script src = "scripts/form.js"></script>	
<div class="container" ng-app="formApp" ng-controller="formController">
   <div class="col-md-6 col-md-offset-3">
      <!-- PAGE TITLE -->
      <div class="page-header">
         <h1><span class="glyphicon glyphicon-tower" style="font-size:20px"></span><span style="font-size:20px; margin-left:10px;">Send a direct e-mail to us</span></h1>
      </div>
      <!-- SHOW ERROR/SUCCESS MESSAGES -->
      <div id="messages" class="well" ng-show="message"></div>
      <!-- FORM -->
      <form ng-submit="processForm()">
         <!-- NAME -->
         <div id="name-group" class="form-group" ng-class="{ 'has-error' : errorName }">
            <label>Name</label>
            <input type="text" name="name" class="form-control" placeholder="Username" ng-model="formData.name">
            <span class="help-block" ng-show="errorName"></span>
         </div>
         <div id="superhero-group" class="form-group" ng-class="{ 'has-error' : errorSuperhero }">
            <label>Email</label>
            <input type="email" name="superheroAlias" class="form-control" placeholder="example@gmail.com" ng-model="formData.superheroAlias">
            <span class="help-block" ng-show="errorSuperhero"></span>
         </div>
         <div id="content-group" class="form-group" ng-class="{ 'has-error' : errorContent }">
            <label>Message</label>
            <textarea  rows="5" cols="50" class="form-control" placeholder="I am user" ng-model="formData.content"></textarea>
            <span class="help-block" ng-show="errorContent"></span>
         </div>
         <button type="submit" class="btn btn-success btn-lg btn-block">
         <span class="glyphicon glyphicon-flash"></span> Submit!
         </button>
      </form>
   </div>
</div>
  1. Set up JS – Observe the following points in the code:
    • $scope.formData used to make glue between model and controller
    • $scope.processForm function making a request to index.php to validate and send the e-mail
    • On success, the successful message, and on failure, the error is assigned to properties
// define angular module/app
    var formApp = angular.module('formApp', []);

    // create angular controller and pass in $scope and $http
    function formController($scope, $http) {

        // create a blank object to hold our form information
        // $scope will allow this to pass between controller and view
        $scope.formData = {};

        // process the form
        $scope.processForm = function () {
            $http({
                method: 'POST',
                url: 'index.php',
                data: $.param($scope.formData),  // pass in data as strings
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }  // set the headers so angular passing info as form data (not request payload)
            })
                .success(function (data) {
                    console.log(data);

                    if (!data.success) {
                        // if not successful, bind errors to error variables
                        $scope.errorName = data.errors.name;
                        $scope.errorSuperhero = data.errors.superheroAlias;
                    } 
                    else {
                        // if successful, bind success message to message
                        $scope.message = data.message;
                    
                    }
                });

        };

    }
  1. Set up PHP file – Observe the following points in the code:
    • class.phpmailer.php is included and referred to send the mail
    • Validation of the values
    • $mail object and its property
    • If the input field is valid then send the e-mailclass.phpmailer.php will also using other classes, so we need to include class.phpmailer.php, class.pop3.php, class.smtp.php, and PHPMailerAutoload.php.
<?php
require_once('class.phpmailer.php');

$errors = array();  	// array to hold validation errors
$data = array(); 		// array to pass back data

// validate the variables 
	if (empty($_POST['name']))
		$errors['name'] = 'Name is required.';

	if (empty($_POST['superheroAlias']))
		$errors['superheroAlias'] = 'E-mail is required.';

	if (empty($_POST['content']))
		$errors['content'] = 'Message is required.';

// return a response

	// response if there are errors
	if ( ! empty($errors)) {

		// if there are items in our errors array, return those errors
		$data['success'] = false;
		$data['errors']  = $errors;
		
	} else {
		$mail = new PHPMailer(); // create a new object
		$mail->IsSMTP(); // enable SMTP
		$mail->SMTPAuth = true; // authentication enabled
		$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
		$mail->Host = "smtp.gmail.com";
		$mail->Port = 465; // or 587
		$mail->IsHTML(true);
		$mail->Username = ""; //Email that you setup
		$mail->Password = ""; // Password
		$mail->Subject = "Y-Web Contact mail from " . $_POST['name'] . ", e-mail: " .$_POST['superheroAlias']. "";
		$mail->Body = $_POST['content'];
		$mail->AddAddress(""); //Pass the e-mail that you setup
		 if(!$mail->Send())
		    {
		    		echo "Mailer Error: " . $mail->ErrorInfo;
		    }
		    else
		    {
		    	$data['success'] = true;
	    		$data['message'] = 'Thank you for sending e-mail.';
		    }
	}
	echo json_encode($data);

Leave a Reply

Your email address will not be published. Required fields are marked *