Using Gmail API to Send Rich Text Emails

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.


  // We only need permissions to compose and send emails
  $service = new Google_Service_Gmail($client);

  // Redirect the URL after OAuth
  if (isset($_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']) {
  } 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();
        $service->users_messages->send("me", $msg);

    } catch (Exception $e) {

  } ?>

Send Mail