Simple way to send email via gmail api using php, tutorial and example to send message using gmail api, and download php script.

How To Send Email Via Gmail API Using PHP

Using PHP cURL and Gmail API we will send email easily, I made “Gmail API Script” using PHP to send messages via Gmail API easily, we will use it in this tutorial.

Live Demo

Go to Gmail API Script and Sign in with Gmail and send message.

Create A Project

Firstly go to this tutorial and read “Create A Project” section, now create your project and enable Gmail API, after that we need “redirect_uri” and “client_id” and “client_secret” to use it in Gmail API Script.

Gmail API Script

Download Gmail API Script.

Now we will learn how to use Gmail API Script, open config.php file, and enter your “redirect_uri” and “client_id” and “client_secret”:

<?php

/* By Qassim Hassan, wp-time.com */

$scope = "https://mail.google.com/"; // Do not change it!

$redirect_uri = "http://XXXX/XX/sign-in.php"; // Enter your redirect_uri

$client_id = "XXXX"; // Enter your client_id

$client_secret = "XXXX"; // Enter your client_secret

$login_url = "https://accounts.google.com/o/oauth2/v2/auth?scope=$scope&response_type=code&redirect_uri=$redirect_uri&client_id=$client_id"; // Do not change it!

?>

Now open index.php file in your browser and Sign in with Gmail:

gmail api sign in

After logged in:

send email using gmail api

In “Subject” field enter your message subject, and in “To” field enter email address to send message to him, and in “Message” field enter your message, if the message has been sent you will find the message on “Sent Box” in your gmail account. If sent:

gmail api message sent

Notes

Access token is valid for one hour only, if expired, sign in again to get new access token.

You can send email to a lot of addresses, use comma between email address in “To” field, for example:

mohammed-ali@gmail.com, jawad-barrak@gmail.com, mohanned-different@gmail.com

Your “redirect_uri” must to be same sign in link “/sign-in.php”, for example:

http://example.com/gmail/sign-in.php
Or:
http://example.com/sign-in.php

Do not forget to enable “Gmail API” on Google Developers Console.