PHPMailer sending Mail using Gmail Smtp

4 Sep

PHP is the most used class to send emails in a PHP Application. It is being used from years wtih the PHP Applications. Now this class is available in https://packagist.org/.    And you can install it with the command

composer require phpmailer/phpmailer

if you are going to build any php application  using core php then you should first install the composer.

Then your first command should composer init. This command generates configuration file for packages and dependencies and then you can install phpmailer vai command given above.

When you execute this command it automatically creates a vendor directory.

You can include and use all classes installed vai composer using below statement in you php application.

require ‘./vendor/autoload.php’;

Now After installing phpmailer you can instantiate a phpmailer object in you php code. In this article we wil discuss how we can send mail vai phpmailer using gmail smtp server.

We use gmail smtp server to send email.

Below example shows you how to send mail using PHPMailer and gmail account. In your gmail account you need to set two step verification. then you need to generate app password.
To create app password you can read this article.
Below is the Example of sending mail using PHPMailer and Gmail Smtp server.


$smtp_host = 'smtp.gmail.com';
$smtp_port = 587;
$smtp_username = 'gmail address';
$smtp_password = 'app password'; // this is diffrence from gmail login password.
$stmp_secure = 'TLS';

$mail = new PHPMailer;
$mail->SMTPDebug = 0;
$mail->IsSMTP(); // Set mailer to use SMTP
$mail->Host = $smtp_host; // Specify main and backup server
$mail->Port = $smtp_port; // Set the SMTP port
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = $smtp_username; // SMTP username
$mail->Password = $smtp_password; // SMTP password
$mail->SMTPSecure = $stmp_secure; // Enable encryption, 'ssl' also accepted
$mail->setFrom($from_email,$from_name);
$mail->AddAddress('john@example.com' ,'john'); // Add a recipient
$mail->addCC('stevan@example.com','stevan'); // Add a recipient

$mail->IsHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $message;
$mail->AltBody = $message;


if(!$mail->Send()) {
//return $mail->ErrorInfo;
return false;
}else {
return true;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

5 × 1 =