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
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:
After logged in:
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:
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.
14 Comments
septiyo
Hi ,
Thanks for your tutorial.
by the way,
can $redirect_uri set to my localhost?
thanks in advace
Qassim Hassan
Yes, you can.
padma
Very nice tutorial.Useful for me.Thank you.
Mamoon
Very helpful, thanks.
kanupriya
Very Helpful tutorial, I have done with this and works correctly.
Amol
Best Tutorial …!
Amol
Can you provide same** tutorial for outlook
Qassim Hassan
Maybe, thanks.
Amol
Update me when you will create outlook tut
Qassim Hassan
Ok :)
Amol
How can i send mail attachment with this script
Azis Hapidin
I want convert this code to Laravel Package, apakah anda mengizinkan? saya akan memasukan nama anda dalam package ini. Please reply to my email
Qassim Hassan
Ya, saya setuju untuk memasukkan nama saya.
swap
amazing code – and its working very well