Using Gmail API to Send Rich Text Emails

U
Published in: Gmail - PHP

The new HTML Mail app uses the Gmail API to send rich-text emails to anyone on your behalf. You can sign-in using your Google / Gmail account via OAuth and are presented with a HTML5 form to send emails. Unlike the Apps Script based solutions that require full access to your Gmail account, the new Gmail API only needs permissions to compose and send messages and does not have access to your Gmail messages and folders.

The app uses the Google PHP library to connect to the Gmail API though the can be easily ported to JavaScript, Python or Java. The text editor of the HTML Mail app is powered by TinyMCE.


<?php

session_start();

require_once 'Google/Client.php';
require_once 'Google/Service/Gmail.php';

// Replace this with your Google Client ID
$client_id     = 'apps.googleusercontent.com';
$client_secret = 'Your Google Client Secret';
$redirect_uri  = 'http://ctrlq.org/'; // Change this

$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);

// We only need permissions to compose and send emails
$client->addScope("https://www.googleapis.com/auth/gmail.compose");
$service = new Google_Service_Gmail($client);

// Redirect the URL after OAuth
if (isset($_GET['code'])) {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

// If Access Toket is not set, show the OAuth URL
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  $client->setAccessToken($_SESSION['access_token']);
} else {
  $authUrl = $client->createAuthUrl();
}

if ($client->getAccessToken() && isset($_POST['message'])) {

  $_SESSION['access_token'] = $client->getAccessToken();

  // Prepare the message in message/rfc822
  try {

      // The message needs to be encoded in Base64URL
      $mime = rtrim(strtr(base64_encode($_POST["message"]), '+/', '-_'), '=');
      $msg = new Google_Service_Gmail_Message();
      $msg->setRaw($mime);
      $service->users_messages->send("me", $msg);

  } catch (Exception $e) {
      print($e->getMessage());
      unset($_SESSION['access_token']);
  }

} ?>

<? if ( isset ( $authUrl ) ) { ?>
<a href="<?= $authUrl; ?>"><img src="google.png" title="Sign-in with Google" /></a>
<? } else { ?>
<form method="POST" action="">
  <textarea name="message" required></textarea>
  <input type="email" required name="to">
  <input type="text"  required name="subject">
  <a href="#" onclick="document.forms.htmlmail.submit();return false;">Send Mail</a>
</form>
<? } ?>
📮  Subscribe to our Email Newsletter for Google tips and tutorials!
Published in: Gmail - PHP

Looking for something? Find here!

Meet the Author

Web Geek, Google Developer Expert
A
Amit Agarwal

Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India. He is the developer of Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory

Get in touch

Google Add-ons

Do more with your Gmail and GSuite account
G

We build bespoke solutions that use the capabilities and the features of Google Workspace for automating business processes and driving work productivity.

  1. Mail Merge with Attachments
    Send personalized email to your Google Contact with a Google Sheet and Gmail
  2. Save Emails and Attachments
    Download email messages and file attachments from Gmail to your Google Drive
  3. Google Forms Email Notifications
    Send email notifications to multiple people when a new Google Form is submitted
  4. Document Studio
    Create beautiful pixel perfect documents merging data from Google Sheets and Google Forms
  5. Creator Studio for Google Slides
    Turn your Google Slides presentations into animated GIFs and videos for uploading to YouTube