send email using phpmailer
Posted on / by Vivan Web Solution / in Angular JS

How To Send Email Using PHPMailer And Angular JS

hello there, in this tutorial we will discuss send Email Using phpmailer and Angular JS. So we need to go through the basics of phpmailer and how to use the service of phpmailer? so let’s start with the basics.

what is PHPMailer ?

Many PHP developers need to send emails from their code. The only PHP function that supports this directly is mail(). However, it does not provide any assistance for making use of popular features such as encryption, authentication, HTML messages, and attachments.

Formatting email correctly is surprisingly difficult. There are myriad overlapping (and conflicting) standards, requiring tight adherence to horribly complicated formatting and encoding rules – the vast majority of code that you’ll find online that uses the mail() function directly is just plain wrong, if not unsafe!

The PHP mail() function usually sends via a local mail server, typically fronted by a sendmail binary on Linux, BSD, and macOS platforms, however, Windows usually doesn’t include a local mail server; PHPMailer’s integrated SMTP client allows email sending on all platforms without needing a local mail server. Be aware though, that the function should be avoided when possible; it’s both faster and safer to use SMTP to localhost.

Features Of PHPMailer.

  • Probably the world’s most popular code for sending email from PHP!
  • Used by many open-source projects: WordPress, Drupal, 1CRM, SugarCRM, Yii, Joomla! and many more
  • Integrated SMTP support – send without a local mail server
  • Send emails with multiple To, CC, BCC and Reply-to addresses
  • Multipart/alternative emails for mail clients that do not read HTML email
  • Support for UTF-8 content and 8bit, base64, binary, and quoted-printable encodings
  • SMTP authentication with LOGIN, PLAIN, CRAM-MD5, and XOAUTH2 mechanisms over SMTPS and SMTP+STARTTLS transports
  • Validates email addresses automatically
  • Protects against header injection attacks

if you want to know more about it please visit this link.

How To Send Email Using PHPMailer?

so in this tutorial, we gonna use phpmailer as we use in PHP and we will use the ajax method in this tutorial so if you don’t know how to use ajax in angular js, please learn from our previous tutorial which you can visit directly from here.

Send Email Using PHPMailer And Angular JS.

so here we will discuss that how to integrate PHPMailer with and how to send Emails using phpmailer and angular js. so here we need to create one simple form using HTML, CSS, or bootstrap. here we created a form using bootstrap so let’s check out that form.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">
  <title>Send Email Using Angular JS</title>
  <!-- Bootstrap core CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body>
  <div class="container-fluid" ng-app="mailApp" ng-controller="mailC">
      <div class="row">
  	 <div class="col-md-12">
            <div class="d-flex justify-content-center col-md-12">
               <form name="Form1">
  		 <h1>Send Email Using Angular JS and PHPMailer</h1>
  		<div id="msg"></div>
  		<label>Enter Reciver Email Address</label>
  		<input type="email" name="rEmail" ng-model="receiver_email" class="form-control" required>
  		<label>Subject</label>
                <input type="text" ng-model="subject" class="form-control">
                <label>Enter Message</label>
  		<textarea class="form-control" cols="12" rows="5" ng-model="message"></textarea>
               <div class="d-flex justify-content-center">
  	       <button class="btn btn-secondary mt-3" ng-click="sendEmail()">Send Email</button>
            <div>
  	</form>
     </div>
  </div>
 </div>
</div>	
  <!-- Bootstrap core JavaScript -->
  <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>

here is the output for the above code.

send email using phpmailer

here we provided an email address, subject, and message you have to fill this form and submit this form here we see how to submit this form using angular JS.

setting up angular js for submitting form.

<script>
    var app = angular.module('mailApp', []);
    app.controller('mailC',function($scope,$http){
    $scope.sendEmail = function(){
    $http.post('api/sendEmail.php',{'receiverEmail':$scope.receiver_email,'subject':$scope.subject,'message':$scope.message}).then(function(res){
          $scope.reciver_email = "";
          $scope.subject = "";
          $scope.message = "";
          $("#msg").append(res.data);
        });
      }
    });
  </script>

so you can see that we did call the sendEmail.php file and we used ajax for the send email using phpmailer.

send email using phpmailer

we completed the front-end of this tutorial now we have to move to the backend.

<?php
error_reporting(0);
$data = json_decode(file_get_contents("php://input"),true);
$receiverEmail = $data['receiverEmail'];
$subject = $data['subject'];
$message = $data['message'];
	use PHPMailer\PHPMailer\PHPMailer;
  	use PHPMailer\PHPMailer\Exception;
    
  	require '../vendor/autoload.php';
    
  	  $mail = new PHPMailer(true);
    
      $mail->isSMTP();                                            
      $mail->Host       = 'smtp.gmail.com;';                    
      $mail->SMTPAuth   = true;                             
      $mail->Username   = 'your email address';                 
      $mail->Password   = 'your email password';                        
      $mail->SMTPSecure = 'tls';                              
      $mail->Port       = 587;  
      $mail->setFrom('your Email address', 'your nick name for email');           
      $mail->addAddress($reciverEmail);
      $mail->isHTML(true);                                  
      $mail->Subject = $subject;
      $mail->Body    = $message;
      $mail->AltBody = 'Body in plain text for non-HTML mail clients';
      try{
      if($mail->send()){
        echo '<div class="alert alert-success alert-dismissible fade show" role="alert">
    <strong>Success !</strong> your Email is sent.
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
    </button>
    </div>';
      }
  } catch (Exception $e) {
      echo '<div class="alert alert-danger alert-dismissible fade show" role="alert">
    <strong>Success !</strong> your Email is Not sent.
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
    </button>
    </div>';
  }
  
?>

so here it is completed with the front-end as well as the backend if you want to learn how to send SMS using PHP then visit this link.

Leave a Reply