Gmail is arguably the most acclaimed email service at the moment. Today more than 1.8 billion clients have its virtual mailboxes, largely due to the possibility of free use. Also, this service offers the widest range of features, from spell checking to marking conversation streams using tags, which makes it convenient for use by anyone.
One example of advanced use of Gmail is implementing its API. In this article, I’ll share the expertise of our dev team on how to set up Gmail API in PHP.
API VS SMTP
First, we need to compare the use of API and SMTP for Gmail email sending. Google’s service grants access to messages using email protocols. The latter here is responsible for email sending since it’s outbound email protocol.
Google’s MTA establishes a TCP connection to an SMTP server and sends an email. After authorization, the server sends an email to the recipient’s SMTP server, which in turn redirects it to the IMAP4 or POP3 server.
In general, various APIs offer a streamlined opportunity for applications, frameworks, and codes to communicate with each other. You can integrate Gmail API to establish a connection between your app and Gmail to send emails. Even more, HTTP may be enough to send emails with Gmail API.
Regarding access, SMTP provides full access to the account using the client’s SMTP authentication login and password. Gmail API uses Open Authentication (OAuth 2.0), which allows you to request only the amount of access you need.
It is especially important because when working with mail, you must take into account the existing restrictions on the number of messages sent, the possible amount of forwarding, the maximum number of recipients, and other blockers. Gmail API has a limit of one billion quota units per day.
Note: keep in mind that the maximum Gmail message size is 50MB with not more than 25MB of attachments.
On the other hand, a third-party API application can request access only to send emails (not read), or read only (but not send); or only to change labels for emails and threads, or only to search for specific items.
What to use for PHP?
No surprise, both options are legit for PHP.
SMTP is a widespread and easy-to-configure solution for sending emails. You don’t need deep programming skills to handle all sorts of things. Moreover, you can benefit from using default Gmail, setting custom mailing services, or even using a testing SMTP server for email testing. However, SMTP might have speed and security issues.
On the contrary, Gmail API is a faster appliance. It is also a great option for automating processes and providing a wide range of functionality for users. The API has an extra layer of security, which is critical if you are dealing with sending confidential data via email.
Why you should choose PHP and Gmail API
While many developers share points against using PHP due to its messy code nature, the language remains a valid solution.
Businesses continue to use desktop/web apps and websites built in PHP frameworks. This language isn’t dead, and it has diverse cross-functionality, including email sending options.
Why Gmail API and PHP? In short, they give you access to Gmail excessive features and allows you automating the process:
- You can automate sending and receiving HTML emails.
- Given the email ID from the search request or history, you can download its content using the messages.get operation.
- You can back up your entire account from start to finish. The API allows you to flip through messages in your account using the messages.list method.
- You can sync the mailbox with your application and even learn about custom filtering settings for messages of a particular type.
- You can add and remove shortcuts that are applied to messages and topics.
- Run specific queries, such as filtering, labeling, or deleting an email.
5 Steps to send emails with PHP and Gmail API
Let’s overview the steps to make your PHP app send emails with Gmail API.
Setting up the project
- Go to Google Developers Console.
- Choose “Select a project” and make a new one. Name it and hit the “Create” button.
- On the left bar, choose “Library” and move to the API Library page. Find Gmail API and click on it. Enable the API for the chosen project.
- Once the API is enabled, you will be taken to a Credentials dashboard. There, select the “OAuth Client ID” from the Create Credentials dropdown list.
- Then you’ll see the “Configure consent” button. By clicking, you’ll get to the page where you can simply enter the name of your application and specify the authorized domains. Please fill in the other fields if you wish.
- Click “Save” and choose your app type (Web App, Android, Chrome App, iOS, or other). After that, name your OAuth Client ID. Also, enter JavaScript sources and redirect domains to use with requests from the browser or web server. Click “Create” to complete.
You set up the project, and now, it’s time to choose a guide and API library.
Guide & API library
You should choose a quickstart guide based on the app framework.
Use Google’s Official Quickstarts. Here, except for PHP, you can find guides for Java, Python, and other popular frameworks as well as guides for iOS and Android APIs.
You’ll first need the Prerequisites section. In the case of PHP, make sure your PHP version matches the given one and install the Google Client Library for PHP.
Note: the JSON extension and Composer Dependency Management Tool are required as well.
Example of API for PHP installation via Composer:
composer require google/apiclient:"^2.0"
The other variations for every primary programming language are here.
Access to Gmail
At this point, you need to authorize access to your Gmail account from your PHP app. To do this, you need to create a file in your working directory:
Directory: gmail/quickstart/ Code sample Run with: php quickstart.php
You will then be prompted to either sign in to your Google account or select one account to authorize. Code sample for PHP is available in this GitHub directory.
After the authorization, your Gmail API is connected. It’s time for you to create your first email.
Create an email
Your PHP app can use the drafts.create method to create a message, which includes:
- Create MIME message
- Convert message to base64url encoded string
- Create a draft
In practice, the process for PHP looks like this:
/** * @param $sender string sender email address * @param $to string recipient email address * @param $subject string email subject * @param $messageText string email text * @return Google_Service_Gmail_Message */ function createMessage($sender, $to, $subject, $messageText) { $message = new Google_Service_Gmail_Message(); $rawMessageString = "From: <{$sender}>\r\n"; $rawMessageString .= "To: <{$to}>\r\n"; $rawMessageString .= 'Subject: =?utf-8?B?' . base64_encode($subject) . "?=\r\n"; $rawMessageString .= "MIME-Version: 1.0\r\n"; $rawMessageString .= "Content-Type: text/html; charset=utf-8\r\n"; $rawMessageString .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n"; $rawMessageString .= "{$messageText}\r\n"; $rawMessage = strtr(base64_encode($rawMessageString), array('+' => '-', '/' => '_')); $message->setRaw($rawMessage); return $message; } /** * @param $service Google_Service_Gmail an authorized Gmail API service instance. * @param $user string User's email address * @param $message Google_Service_Gmail_Message * @return Google_Service_Gmail_Draft */ function createDraft($service, $user, $message) { $draft = new Google_Service_Gmail_Draft(); $draft->setMessage($message); try { $draft = $service->users_drafts->create($user, $draft); print 'Draft ID: ' . $draft->getId(); } catch (Exception $e) { print 'An error occurred: ' . $e->getMessage(); } return $draft; }
Send an email
What you have composed can now be sent to the recipient using commands messages.send or draft.send
The complete command scenario for PHP has the following shape:
/** * @param $service Google_Service_Gmail an authorized Gmail API service instance. * @param $userId string User's email address * @param $message Google_Service_Gmail_Message * @return null|Google_Service_Gmail_Message */ function sendMessage($service, $userId, $message) { try { $message = $service->users_messages->send($userId, $message); print 'Message with ID: ' . $message->getId() . ' sent.'; return $message; } catch (Exception $e) { print 'An error occurred: ' . $e->getMessage(); } return null; }
Wrap up
Gmail API and your PHP app can become good friends when it comes to email sending. Using this combination, you’ll be able to add a bit of security and speed to the email sending. Besides, all needed help from Google is available, and any whim can be materialized.
Tyler Lazenby says
I appreciate the starting point here. But where is more documentation on how to set up the message? I would like to use more headers for example.