PHP - send mail using gmail smtp

  • Go to the https://myaccount.google.com/lesssecureapps and enable "Allow less secure apps"
  • Install composer if doesn't already exists
  • Install phpmailer library with command - composer require phpmailer/phpmailer
  • Copy the code from above and paste it into your index.php file
  • Execute created file with command - php index.php
require 'vendor/autoload.php';

use PHPMailer\PHPMailer\PHPMailer;

$mail = new PHPMailer(true);

try {
    $mail->isSMTP();
    $mail->SMTPAuth = true;
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;
    $mail->Host = 'smtp.gmail.com';
    $mail->Username = 'yourgmail@gmail.com';
    $mail->Password = 'yourgmailpassword';

    $mail->setFrom('yourgmail@gmail.com', 'Superman');
    $mail->addAddress('clientmail@mail.ru', 'Batman');
    $mail->Subject = 'Battle';
    $mail->Body = 'Your text here.';

    $mail->send();
} catch (PHPMailer\PHPMailer\Exception $e) {
    echo $e->errorMessage();
} catch (\Exception $e) {
    echo $e->getMessage();
}