How to Use PHPMailer in PHP
PHPMailer is an important and most useful library to send email easily, sometimes the PHP default mail() function does not work properly then there is a need of a PHPMailer. PHPMailer is used to send mail by localhost, it works very well on localhost.
Let’s see the following steps to use PHPMailer:
Step1: Download PHPMailer from GitHub, you can download the link below given the link:
https://github.com/PHPMailer/PHPMailer
Step2: After download extract the folder and put only the src folder in your project directory, src folder contains all the necessary classes file of PHPMailer.
Step3: create phpmailer.php file to check to send mail functionality of PHPMailer, write the following code:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';
//require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$mail->SMTPDebug = 2;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com;';
$mail->SMTPAuth = true;
$mail->Username = 'your-gmail-id';
$mail->Password = 'your-gmail-id-password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('your-gmail-id', 'Name');
$mail->addAddress('client-gmail-id'); // where you want to send mail
$mail->isHTML(true);
$mail->Subject = 'Subject';
$mail->Body = 'HTML message body in <b>bold</b> ';
$mail->AltBody = 'Body in plain text for non-HTML mail clients';
$mail->send();
echo "Mail has been sent successfully!";
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?>
Note: There are some important points to keep in mind to use PHPMailer :
- Disable Gmail 2 Step Verification
- Turn on less secure apps form Gmail security