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:

Download PHPMailer from GitHub, you can download the link below given the link:

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.

create phpmailer.php file to check to send mail functionality of PHPMailer, write the following code:

 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->Host        = ';';                                                        
             $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->Subject = 'Subject'; 
             $mail->Body = 'HTML message body in <b>bold</b> '; 
             $mail->AltBody = 'Body in plain text for non-HTML mail clients'; 
             echo "Mail has been sent successfully!"; 
 } catch (Exception $e) { 
             echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"; 

There are some important points to keep in mind to use PHPMailer :

  1. Disable Gmail 2 Step Verification
  2. Turn on less secure apps form Gmail security

Download Source Code

Categories: web development php

Trending Courses


Regular : 45 Days

Fastrack : 20 Days

Crash : 10 Days

Advance Digital Marketing Expert Course

Regular : 6 Months

Fastrack : 3 Months

Crash : 2 Months

React JS

Regular : 45 Days

Fastrack : 25 Days

Crash : 15 Days


Regular : 45 Days

Fastrack : 20 Days

Crash : 10 Days

Front End Developer

Regular : 6 Months

Fastrack : 4 Months

Crash : 2 Months

Web Expert with Python

Regular : 12 Months

Fastrack : 6 Months

Crash : 3 Months

Related Blogs

Request For Demo