Gmail SMTP New Method 2023 – PHP

In this tutorial, I am going to show you, how you can use Gmail SMTP for sending emails in PHP.

Video tutorial – Gmail SMTP in PHP

I will be using PHPMailer library. You can find all the code for sending email from PHPMailer documentation.

<?php

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

require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';

//Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      //Enable verbose debug output
    $mail->isSMTP();                                            //Send using SMTP
    $mail->Host       = 'smtp.gmail.com';                     //Set the SMTP server to send through
    $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
    $mail->Username   = 'your_email_address@gmail.com';                     //SMTP username
    $mail->Password   = 'app_password';                               //SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
    $mail->Port       = 465;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

    //Recipients
    $mail->setFrom('your_email_address@gmail.com', 'Your name');
    $mail->addAddress('support@adnan-tech.com', 'Adnan Tech');

    //Content
    $mail->isHTML(true);                                  //Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

Line #18: You need to set your host to smtp.gmail.com

Line #20: Write your email address

Line #21: Write the app password you will get from your google account in the next step.

First, you need to go to your google account.

Manage google account
Manage google account

Go to security.

Security
Security

Then go to 2-step verification.

2-step verification
2-step verification

After that, go to app passwords.

App passwords
App passwords

Set whatever name you want and generate.

This will generate an app password.

App password for Gmail SMTP - PHP
App password for Gmail SMTP – PHP

You can use this in your SMTP code. Line #21 of the above code.

Make sure there is no space in password. Then try again. You should receive an email now.

Learn how to do it in Node JS from here.

If you need any help in following this, kindly do let me know.

Hosting email address send SMTP email in PHP

In this tutorial, we will teach you how to send email from a hosting email address using SMTP in PHP. Recently, Google has disabled its “less secure apps” option. This means that you can no longer send SMTP emails from your Gmail account.


So, today we are going to show you, how you can send SMTP emails from your own hosting email address.

Step 1: Login to cPanel

First step, is to login to your hosting provider and open cPanel. In your cPanel, search for “email” and goto “Email accounts”.

Step 2: Search email address

Then search for desired email address, from which you want to send emails and select “Check email”.

Step 3: Open mail client configurations

On the next page, you need to look for the section “Other webmail features” and click on the “Configure mail clients” box.

Step 4: Check SMTP details of your hosting email address

From here, you need to loop for the following configurations.

Step 5: Send SMTP email

Now, we need to install a library called PHPMailer. Open the command prompt at the root of your project and run the following command:

> composer require phpmailer/phpmailer

Make sure you have downloaded the composer from here. Write the following code in the file from where you want to send the email:

// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

//Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);

try
{
    //Enable verbose debug output
    $mail->SMTPDebug = 0; // SMTP::DEBUG_SERVER;

    //Send using SMTP
    $mail->isSMTP();

    //Set the SMTP server to send through
    $mail->Host = "mail host address";

    //Enable SMTP authentication
    $mail->SMTPAuth = true;

    //SMTP username
    $mail->Username = "email address";

    //SMTP password
    $mail->Password = "password";

    //Enable TLS encryption;
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;

    //TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
    $mail->Port = 587;

    //Recipients
    $mail->setFrom("email address", "your name");

    //Add a recipient
    $mail->addAddress("recipient email address", "recipient name");

    //Set email format to HTML
    $mail->isHTML(true);

    $mail->Subject = "subject";
    $mail->Body    = "body";

    $mail->send();
    echo 'Message has been sent';
}
catch (Exception $e)
{
    die("Message could not be sent. Mailer Error: " . $mail->ErrorInfo);
}

So that’s it. That’s how you can send emails from your hosting email address using SMTP in PHP. If you want to attach files with the email, we have already created a separate tutorial on that. If you face any problems in following this, kindly do let me know.

How to check if email is read by user – PHP, Gmail, Outlook

Problem:

If you are developing a web project that includes sending emails to users, then it is very important for you to know if those emails are being read or delivered to those users. For example, if you are sending marketing emails to your subscriber’s list, then it is essential for you to know that your email is read by which users. And by which users the email is not read yet.

This will greatly help you to make decisions if you are sending the right emails or not. Because if the user can read your marketing email, but didn’t buy anything from you, it clearly means there was something wrong with the email. But how do you know if the email sent from PHP, Laravel, or whatever framework you are using, is being opened by the user?

Solution:

Follow this tutorial, and you will be able to add such functionality in your web project.

Sending the email:

For sending the email, you can use the popular “PHPMailer” library. You can also use built-in PHP “mail()” function. Open command prompt or Terminal in your project root folder and run the following command (make sure you have composer installed in your system):

composer require phpmailer/phpmailer

This will create a “vendor” folder in your project root folder. Create a table in your MySQL database named “emails” and it will have 4 columns:

  1. ID (INTEGER) (primary key, auto_increment, not null)
  2. email (TEXT) (not null)
  3. content (TEXT) (not null)
  4. read_at (DATETIME) (null)
How to check if email is read by user - PHP, Gmail, Outlook - Emails table
How to check if email is read by user – PHP, Gmail, Outlook – Emails table

Send email using the following code in your PHP file:

<?php

// import PHPMailer classes into the global namespace
// these must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// load Composer's autoloader
require 'vendor/autoload.php';

// instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);

// the person who will receive the email
$recipient = "recipient_email";

// content of email
$content = "This is the HTML message body <b>in bold!</b>";

// connect with database
$conn = mysqli_connect("localhost:8889", "root", "root", "test");

// insert in mails table
$sql = "INSERT INTO emails (email, content) VALUES ('" . $recipient . "', '" . $content . "')";
mysqli_query($conn, $sql);

// get inserted mail ID
$email_id = mysqli_insert_id($conn);

// append empty image tag with email content
// this will help to know when user read that email
$base_url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$content .= "<img src='" . $base_url . "email_read.php?email_id=" . $email_id . "' style='display: none;' />";

try {
    // disable verbose debug output
    $mail->SMTPDebug = 0;

    // send using SMTP
    $mail->isSMTP();

    // set the SMTP server to send through
    $mail->Host = 'smtp.gmail.com';

    // enable SMTP authentication
    $mail->SMTPAuth = true;

    // SMTP username
    $mail->Username = 'your_email@gmail.com';

    // SMTP password
    $mail->Password = 'your_password';

    // enable TLS encryption
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;

    // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
    $mail->Port = 587;

    $mail->setFrom('your_email@gmail.com', 'Your name');

    // add a recipient
    $mail->addAddress($recipient);

    // set email format to HTML
    $mail->isHTML(true);
    $mail->Subject = 'Here is the subject';
    $mail->Body = $content;

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

You just need to change the email and password with your Gmail address and password. To learn more about configuring an SMTP server, read this.

[do_widget id=custom_html-4]

This is how the email will be received in the user’s inbox (image will not be visible):

A sample mail
How to check if email is read by user – PHP, Gmail, Outlook – Inbox

View emails and time they are read:

Now, we will create a separate page for the admin where he/she can see a list of all emails sent from the website along with the time they are read by the user. Create a file named “view_emails.php” and paste the following code in it:

<?php

// connect with database
$conn = mysqli_connect("localhost:8889", "root", "root", "test");

// get all emails
$sql = "SELECT * FROM emails";
$result = mysqli_query($conn, $sql);

?>

<!-- basic style of table -->
<style>
    table, td {
        border: 1px solid black;
        border-collapse: collapse;
        padding: 25px;
    }
</style>

<table>

    <?php

    // show all emails
    while ($row = mysqli_fetch_object($result))
    {
        ?>
        <tr>
            <td><?= $row->id; ?></td>
            <td><?= $row->email; ?></td>
            <td><?= $row->content; ?></td>
            <td><?= $row->read_at == null ? "Not read" : $row->read_at; ?></td>
        </tr>
        <?php
    }

    ?>

</table>

Access this page directly and you will see a list of all emails with the time they are read (next step).

How to check if email is read by user - PHP, Gmail, Outlook - Not read
How to check if email is read by user – PHP, Gmail, Outlook – Not read

Mark the time when email is read:

Create a file named “email_read.php” and paste the following code in it:

<?php

// this page will be executed only when the email is opened by user

// connect with database
$conn = mysqli_connect("localhost:8889", "root", "root", "test");

// get email ID
$email_id = $_GET["email_id"];

// update read_at value in emails table
$sql = "UPDATE emails SET read_at = NOW() WHERE id = '" . $email_id . "'";
mysqli_query($conn, $sql);

[do_widget id=custom_html-4]

You will never see the output from this file but it will mark the time in database when the email is read.

How to check if email is read by user – PHP, Gmail, Outlook – Read

Let me know if you had any problem in following this tutorial.

[wpdm_package id=’1170′]