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 https://github.com/PHPMailer/PHPMailer and extract zip file into PHPMailer folder. The following example shows, how to send mail using PHPMailer in PHP.

Example :
<?php 
  //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       = 'smtp.servername.com';  //Set the SMTP server. For ex 'smtp.hostinger.com'
    $mail->SMTPAuth   = true;  //Enable SMTP authentication
    $mail->Username   = 'user@servername.com';  //SMTP username
    $mail->Password   = 'password';  //SMTP password
    $mail->SMTPSecure = 'tls';  //Enable implicit TLS encryption
    $mail->Port       = 587; //TCP port to connect to;
  
    //Recipients
    $mail->setFrom('from@servername.com', 'Name');   // Set sender
    $mail->addAddress('receiver1@example.com", "Receiver1 Name');  //Add a recipient1
    $mail->addAddress('receiver2@example.com", "Receiver2 Name');  //Add a recipient2

    //Attachments
    $mail->addAttachment('/uploads/1.pdf');  
    $mail->addAttachment('/uploads/2.pdf','Invoice');  
  
    //Content
    $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';
     
  
    $mail->send();
    echo 'Message has been sent';
     
  }catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
  }
?>