SMTP setting in php by using gmail

Sending email is a simple and straightforward task in PHP. Yes! trust me. For some beginners and sometimes even the experienced too struggle to send an email using PHP.

Download phpmailer library from 
https://github.com/PHPMailer/PHPMailer or use this command
composer require phpmailer/phpmailer

Turn on 2-Step Verification (required for App Passwords):

Goto your gmail account and click manage your google account. Click profile button and click manage your google account.
Click on security option which is appear on the left sidebar.
Enable two step verification first and then Goto to this link:
https://myaccount.google.com/apppasswords
(dont use inside the if statement)

<?php 

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

//Load Composer's autoloader

require 'vendor/autoload.php';
include('dbcon.php');

$email = $_POST['email'];
$q = "SELECT * FROM students2 WHERE email = '$email'";
$result = $conn->query($q);

if ($result->num_rows > 0) {

while($row = $result->fetch_assoc()) {
        $token = $row["tempory_token"];
    }

// create object of PHPMailer class with boolean parameter which sets/unsets exception.

        $mail = new PHPMailer(true);                              

        try {
            $mail->isSMTP(); // using SMTP protocol                                     
            $mail->Host = 'smtp.gmail.com'; // SMTP host as gmail 
            $mail->SMTPAuth = true;  // enable smtp authentication                             
            $mail->Username = 'funystory23654@gmail.com';  // sender gmail host              
            $mail->Password = 'kzfk zsvj xsgx pars'; // sender gmail host password                          
            $mail->SMTPSecure = 'tls';  // for encrypted connection                           
            $mail->Port = 587;   // port for SMTP     
            $mail->isHTML(true); 
            $mail->setFrom('wordpress12389@gmail.com', "Sender"); // sender's email and name
            $mail->addAddress('upwork12389@gmail.com', "Receiver");  // receiver's email and name

            // $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; 
            $mail->Subject = 'Email verification';
            $mail->Body    = 'Please click this button to verify your account: <a href=http://localhost/php/change-password.php?token='.$token.'>Change Password</a>' ;

            $mail->send();
            echo 'Message has been sent';

        } catch (Exception $e) { // handle error.
            echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
        }

}

Leave a Reply