How to use PHPMailer to send an email

The PHPMailer 5.2 directory that’s included with this book’s download

/xampp/htdocs/book_apps/PHPMailer

The GitHub URL that provides more recent versions of PHPMailer

github.com/PHPMailer/PHPMailer

How to use PHPMailer to send an email

Step 1: Load the PHPMailer classes

      set_include_path('/xampp/htdocs/book_apps/PHPMailer'); 
      require_once 'PHPMailerAutoload.php';
      

Step 2: Create the PHPMailer object

      mail = new PHPMailer();
      

Step 3: Set the parameters for the PHPMailer

      object $mail->isSMTP(); // Set mailer to use SMTP
      $mail->Host = 'smtp.gmail.com'; // Set SMTP server 
      $mail->SMTPSecure = 'tls'; // Set encryption type
      $mail->Port = 587; // Set TCP port
      $mail->SMTPAuth = true; // Enable SMTP authentication
      $mail->Username = 'YOUR_USERNAME@gmail.com'; // Set SMTP username 
      $mail->Password = 'YOUR_PASSWORD'; // Set SMTP password 
      $mail->setFrom('johndoe@example.com', 'John Doe'); 
      $mail->addAddress('janedoe@example.com', 'Jane Doe'); 
      $mail->Subject = 'PHPMailer Test'; 
      $mail->Body $mail->AltBody = 'This body does not use HTML.'; 
      $mail->isHTML(true);
      

Step 4: Use the PHPMailer object to send the email

      if($mail->send()) { 
        echo("Message has been sent by PHPMailer.<br />");
      } else { 
        echo("Message could not be sent by PHPMailer.<br />");
        echo("Error: " . $mail->ErrorInfo . "<br />");
      }
      

Description

Back