How to send Mail using PHPMailer in PHP

PHPMailer is a code library, used to send emails from a web server. It an Alternative to PHP's mail() function.PHPMailer provides an object-oriented interface.It has integrated SMTP protocol support and authentication over SSL and TLS.

Download PHPMailer library from and extract zip file into PHPMailer folder. The following example shows, how to send mail using PHPMailer in PHP.

Example :
  //Import PHPMailer classes
  use PHPMailer\PHPMailer\PHPMailer;
  use PHPMailer\PHPMailer\SMTP;
  use PHPMailer\PHPMailer\Exception;

  //Import PHPMailer
  require 'PHPMailer/src/Exception.php';
  require 'PHPMailer/src/PHPMailer.php';
  require 'PHPMailer/src/SMTP.php';
  //passing `true` enables exceptions
  $mail = new PHPMailer(true);
  try {
    //Server settings
    $mail->SMTPDebug = 0;//Enable verbose debug output; 0-default,1-Display output 2-display responses
    $mail->isSMTP();  //Send using SMTP
    $mail->Host       = '';  //Set the SMTP server. For ex ''
    $mail->SMTPAuth   = true;  //Enable SMTP authentication
    $mail->Username   = '';  //SMTP username
    $mail->Password   = 'password';  //SMTP password
    $mail->SMTPSecure = 'tls';  //Enable implicit TLS encryption
    $mail->Port       = 587; //TCP port to connect to;
    $mail->setFrom('', 'Name');   // Set sender
    $mail->addAddress("", "Receiver1 Name");  //Add a recipient1
    $mail->addAddress("", "Receiver2 Name");  //Add a recipient2

    $mail->isHTML(true);  //Set email format to HTML
    $mail->Subject = 'Subject';
    $mail->Body  = 'This is <u>Sample</u> Message';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
    echo 'Message has been sent';
  }catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";