Google Apps Script Library for Gmail API

The Gmail API offers extra functionality not available inside the Gmail service of Google Apps Script. For instance, the ability to purge Gmail folders is available in Apps Script but there’s no option to empty the trash. This can be easily done with the Gmail API. It also support draft creation that is used in Gmail Merge.

Spencer has published a wrapper library that makes it easy to use the Gmail API inside Google Apps Script.

/**
* Google Apps Script Library for the gmail API
*
* Credit: +SpencerEaston 
* Source: https://drive.google.com/folderview?id=0B_j9_-NbJQQDcUNEckk2WGhETms
* 
* OAuth2 Scopes
* https://mail.google.com/
* https://www.googleapis.com/auth/gmail.compose
* https://www.googleapis.com/auth/gmail.insert
* https://www.googleapis.com/auth/gmail.labels
* https://www.googleapis.com/auth/gmail.modify
* https://www.googleapis.com/auth/gmail.readonly
* https://www.googleapis.com/auth/gmail.send
*/

var BASEURL_="https://www.googleapis.com/gmail/v1/users/";
var tokenService_;

/*
* Stores the function passed that is invoked to get a OAuth2 token;
* @param {function} service The function used to get the OAuth2 token;
*
*/
function setTokenService(service){
  tokenService_ = service;
}

/*
* Returns an OAuth2 token from your TokenService as a test
* @return {string} An OAuth2 token
*
*/
function testTokenService(){
 return tokenService_();
}

/**
 * Performs a Fetch
 * @param {string} url The endpoint for the URL with parameters
 * @param {Object.<string, string>} options Options to override default fetch options
 * @returns {Object.<string,string>} the fetch results
 * @private
 */
function CALL_(path,options){
  var fetchOptions = {method:"",muteHttpExceptions:true, contentType:"application/json", headers:{Authorization:"Bearer "+tokenService_()}}
  var url = BASEURL_ + path;
  
  for(option in options){
    fetchOptions[option] = options[option];
  }
  
  var response = UrlFetchApp.fetch(url, fetchOptions)
  if(response.getResponseCode() != 200){
    throw new Error(response.getContentText())
  }else{
    return JSON.parse(response.getContentText());
  }
}

/**
 * Performs a Fetch and accumulation using pageToken parameter of the returned results
 * @param {string} url The endpoint for the URL with parameters
 * @param {Object.<string, string>} options Options to override default fetch options
 * @param {string} returnParamPath The path of the parameter to be accumulated
 * @returns {Array.Object.<string,string>} An array of objects
 * @private
 */
function CALLPAGE_(path,options, returnParamPath){
  var fetchOptions = {method:"",muteHttpExceptions:true, contentType:"application/json", headers:{Authorization:"Bearer "+tokenService_()}}
  for(option in options){
    fetchOptions[option] = options[option];
  }
  var url = BASEURL_ + path;
  var returnArray = [];
  var nextPageToken;
  do{
    if(nextPageToken){
      url += "?pageToken=" + nextPageToken;
    }
    var results = UrlFetchApp.fetch(url, fetchOptions);
    if(results.getResponseCode() != 200){
      throw new Error(results.getContentText());
    }else{
      var resp = JSON.parse(results.getContentText())
      nextPageToken = resp.nextPageToken;
      returnArray  = returnArray.concat(resp[returnParamPath])
    }
  }while(nextPageToken);
  return returnArray;
}

/**
 * Builds a complete URL from a base URL and a map of URL parameters.
 * @param {string} url The base URL.
 * @param {Object.<string, string>} params The URL parameters and values.
 * @returns {string} The complete URL.
 * @private
 */
function buildUrl_(url, params) {
  var params = params || {}; //allow for NULL options
  var paramString = Object.keys(params).map(function(key) {
    return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
  }).join('&');
  return url + (url.indexOf('?') >= 0 ? '&' : '?') + paramString;
}

/**
* Gets the current user's Gmail profile.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {object} options Keypair of all optional parameters for this call
* @return {object} The returned ProfileResource object
*/
function usersGetProfile(userId,options){
  var path = buildUrl_(""+userId+"/profile",options);
  var callOptions = {method:"GET"};
  var ProfileResource = CALL_(path,callOptions);
  return ProfileResource;
}

/**
* Stop receiving push notifications for the given user mailbox.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {object} options Keypair of all optional parameters for this call
*/
function usersStop(userId,options){
  var path = buildUrl_(""+userId+"/stop",options);
  var callOptions = {method:"POST"};
  var removeResource = CALL_(path,callOptions);
  return removeResource;
}

/**
* Set up or update a push notification watch on the given user mailbox.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {object} WatchRequestResource An object containing the WatchRequestResource for this method
* @param {object} options Keypair of all optional parameters for this call
* @return {object} The returned WatchResponseResource object
*/
function usersWatch(userId,WatchRequestResource,options){
  var path = buildUrl_(""+userId+"/watch",options);
  var callOptions = {method:"POST",payload:JSON.stringify(WatchRequestResource)};
  var WatchResponseResource = CALL_(path,callOptions);
  return WatchResponseResource;
}

/**
* Creates a new draft with the DRAFT label.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {object} DraftResource An object containing the DraftResource for this method
* @param {object} options Keypair of all optional parameters for this call
* @return {object} The returned DraftResource object
*/
function usersDraftsCreate(userId,DraftResource,options){
  var path = buildUrl_(""+userId+"/drafts",options);
  var callOptions = {method:"POST",payload:JSON.stringify(DraftResource)};
  var DraftResource = CALL_(path,callOptions);
  return DraftResource;
}

/**
* Immediately and permanently deletes the specified draft. Does not simply trash it.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {string} id The ID of the draft to delete.
* @param {object} options Keypair of all optional parameters for this call
*/
function usersDraftsDelete(userId,id,options){
  var path = buildUrl_(""+userId+"/drafts/"+id,options);
  var callOptions = {method:"DELETE"};
  var removeResource = CALL_(path,callOptions);
  return removeResource;
}

/**
* Gets the specified draft.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {string} id The ID of the draft to retrieve.
* @param {object} options Keypair of all optional parameters for this call
* @return {object} The returned DraftResource object
*/
function usersDraftsGet(userId,id,options){
  var path = buildUrl_(""+userId+"/drafts/"+id,options);
  var callOptions = {method:"GET"};
  var DraftResource = CALL_(path,callOptions);
  return DraftResource;
}

/**
* Lists the drafts in the user's mailbox.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {object} options Keypair of all optional parameters for this call
* @return {object} The returned ListDraftsResponseResource object
*/
function usersDraftsList(userId,options){
  var path = buildUrl_(""+userId+"/drafts",options);
  var callOptions = {method:"GET"};
  var ListDraftsResponseItems = CALLPAGE_(path,callOptions,"items");
  return ListDraftsResponseItems;
}

/**
* Sends the specified, existing draft to the recipients in the To, Cc, and Bcc headers.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {object} DraftResource An object containing the DraftResource for this method
* @param {object} options Keypair of all optional parameters for this call
* @return {object} The returned MessageResource object
*/
function usersDraftsSend(userId,DraftResource,options){
  var path = buildUrl_(""+userId+"/drafts/send",options);
  var callOptions = {method:"POST",payload:JSON.stringify(DraftResource)};
  var MessageResource = CALL_(path,callOptions);
  return MessageResource;
}

/**
* Replaces a draft's content.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {string} id The ID of the draft to update.
* @param {object} DraftResource An object containing the DraftResource for this method
* @param {object} options Keypair of all optional parameters for this call
* @return {object} The returned DraftResource object
*/
function usersDraftsUpdate(userId,id,DraftResource,options){
  var path = buildUrl_(""+userId+"/drafts/"+id,options);
  var callOptions = {method:"PUT",payload:JSON.stringify(DraftResource)};
  var DraftResource = CALL_(path,callOptions);
  return DraftResource;
}

/**
* Lists the history of all changes to the given mailbox. History results are returned in chronological order (increasing historyId).
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {object} options Keypair of all optional parameters for this call
* @return {object} The returned ListHistoryResponseResource object
*/
function usersHistoryList(userId,options){
  var path = buildUrl_(""+userId+"/history",options);
  var callOptions = {method:"GET"};
  var ListHistoryResponseItems = CALLPAGE_(path,callOptions,"items");
  return ListHistoryResponseItems;
}

/**
* Creates a new label.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {object} LabelResource An object containing the LabelResource for this method
* @param {object} options Keypair of all optional parameters for this call
* @return {object} The returned LabelResource object
*/
function usersLabelsCreate(userId,LabelResource,options){
  var path = buildUrl_(""+userId+"/labels",options);
  var callOptions = {method:"POST",payload:JSON.stringify(LabelResource)};
  var LabelResource = CALL_(path,callOptions);
  return LabelResource;
}

/**
* Immediately and permanently deletes the specified label and removes it from any messages and threads that it is applied to.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {string} id The ID of the label to delete.
* @param {object} options Keypair of all optional parameters for this call
*/
function usersLabelsDelete(userId,id,options){
  var path = buildUrl_(""+userId+"/labels/"+id,options);
  var callOptions = {method:"DELETE"};
  var removeResource = CALL_(path,callOptions);
  return removeResource;
}

/**
* Gets the specified label.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {string} id The ID of the label to retrieve.
* @param {object} options Keypair of all optional parameters for this call
* @return {object} The returned LabelResource object
*/
function usersLabelsGet(userId,id,options){
  var path = buildUrl_(""+userId+"/labels/"+id,options);
  var callOptions = {method:"GET"};
  var LabelResource = CALL_(path,callOptions);
  return LabelResource;
}

/**
* Lists all labels in the user's mailbox.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {object} options Keypair of all optional parameters for this call
* @return {object} The returned ListLabelsResponseResource object
*/
function usersLabelsList(userId,options){
  var path = buildUrl_(""+userId+"/labels",options);
  var callOptions = {method:"GET"};
  var ListLabelsResponseResource = CALL_(path,callOptions);
  return ListLabelsResponseResource;
}

/**
* Updates the specified label. This method supports patch semantics.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {string} id The ID of the label to update.
* @param {object} LabelResource An object containing the LabelResource for this method
* @param {object} options Keypair of all optional parameters for this call
* @return {object} The returned LabelResource object
*/
function usersLabelsPatch(userId,id,LabelResource,options){
  var path = buildUrl_(""+userId+"/labels/"+id,options);
  var callOptions = {method:"PATCH",payload:JSON.stringify(LabelResource)};
  var LabelResource = CALL_(path,callOptions);
  return LabelResource;
}

/**
* Updates the specified label.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {string} id The ID of the label to update.
* @param {object} LabelResource An object containing the LabelResource for this method
* @param {object} options Keypair of all optional parameters for this call
* @return {object} The returned LabelResource object
*/
function usersLabelsUpdate(userId,id,LabelResource,options){
  var path = buildUrl_(""+userId+"/labels/"+id,options);
  var callOptions = {method:"PUT",payload:JSON.stringify(LabelResource)};
  var LabelResource = CALL_(path,callOptions);
  return LabelResource;
}

/**
* Immediately and permanently deletes the specified message. This operation cannot be undone. Prefer messages.trash instead.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {string} id The ID of the message to delete.
* @param {object} options Keypair of all optional parameters for this call
*/
function usersMessagesDelete(userId,id,options){
  var path = buildUrl_(""+userId+"/messages/"+id,options);
  var callOptions = {method:"DELETE"};
  var removeResource = CALL_(path,callOptions);
  return removeResource;
}

/**
* Gets the specified message.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {string} id The ID of the message to retrieve.
* @param {object} options Keypair of all optional parameters for this call
* @return {object} The returned MessageResource object
*/
function usersMessagesGet(userId,id,options){
  var path = buildUrl_(""+userId+"/messages/"+id,options);
  var callOptions = {method:"GET"};
  var MessageResource = CALL_(path,callOptions);
  return MessageResource;
}

/**
* Imports a message into only this user's mailbox, with standard email delivery scanning and classification similar to receiving via SMTP. Does not send a message.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {object} MessageResource An object containing the MessageResource for this method
* @param {object} options Keypair of all optional parameters for this call
* @return {object} The returned MessageResource object
*/
function usersMessagesImport(userId,MessageResource,options){
  var path = buildUrl_(""+userId+"/messages/import",options);
  var callOptions = {method:"POST",payload:JSON.stringify(MessageResource)};
  var MessageResource = CALL_(path,callOptions);
  return MessageResource;
}

/**
* Directly inserts a message into only this user's mailbox similar to IMAP APPEND, bypassing most scanning and classification. Does not send a message.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {object} MessageResource An object containing the MessageResource for this method
* @param {object} options Keypair of all optional parameters for this call
* @return {object} The returned MessageResource object
*/
function usersMessagesInsert(userId,MessageResource,options){
  var path = buildUrl_(""+userId+"/messages",options);
  var callOptions = {method:"POST",payload:JSON.stringify(MessageResource)};
  var MessageResource = CALL_(path,callOptions);
  return MessageResource;
}

/**
* Lists the messages in the user's mailbox.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {object} options Keypair of all optional parameters for this call
* @return {object} The returned ListMessagesResponseResource object
*/
function usersMessagesList(userId,options){
  var path = buildUrl_(""+userId+"/messages",options);
  var callOptions = {method:"GET"};
  var ListMessagesResponseItems = CALLPAGE_(path,callOptions,"items");
  return ListMessagesResponseItems;
}

/**
* Modifies the labels on the specified message.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {string} id The ID of the message to modify.
* @param {object} ModifyMessageRequestResource An object containing the ModifyMessageRequestResource for this method
* @param {object} options Keypair of all optional parameters for this call
* @return {object} The returned MessageResource object
*/
function usersMessagesModify(userId,id,ModifyMessageRequestResource,options){
  var path = buildUrl_(""+userId+"/messages/"+id+"/modify",options);
  var callOptions = {method:"POST",payload:JSON.stringify(ModifyMessageRequestResource)};
  var MessageResource = CALL_(path,callOptions);
  return MessageResource;
}

/**
* Sends the specified message to the recipients in the To, Cc, and Bcc headers.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {object} MessageResource An object containing the MessageResource for this method
* @param {object} options Keypair of all optional parameters for this call
* @return {object} The returned MessageResource object
*/
function usersMessagesSend(userId,MessageResource,options){
  var path = buildUrl_(""+userId+"/messages/send",options);
  var callOptions = {method:"POST",payload:JSON.stringify(MessageResource)};
  var MessageResource = CALL_(path,callOptions);
  return MessageResource;
}

/**
* Moves the specified message to the trash.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {string} id The ID of the message to Trash.
* @param {object} options Keypair of all optional parameters for this call
* @return {object} The returned MessageResource object
*/
function usersMessagesTrash(userId,id,options){
  var path = buildUrl_(""+userId+"/messages/"+id+"/trash",options);
  var callOptions = {method:"POST"};
  var MessageResource = CALL_(path,callOptions);
  return MessageResource;
}

/**
* Removes the specified message from the trash.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {string} id The ID of the message to remove from Trash.
* @param {object} options Keypair of all optional parameters for this call
* @return {object} The returned MessageResource object
*/
function usersMessagesUntrash(userId,id,options){
  var path = buildUrl_(""+userId+"/messages/"+id+"/untrash",options);
  var callOptions = {method:"POST"};
  var MessageResource = CALL_(path,callOptions);
  return MessageResource;
}

/**
* Gets the specified message attachment.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {string} messageId The ID of the message containing the attachment.
* @param {string} id The ID of the attachment.
* @param {object} options Keypair of all optional parameters for this call
* @return {object} The returned MessagePartBodyResource object
*/
function usersMessagesAttachmentsGet(userId,messageId,id,options){
  var path = buildUrl_(""+userId+"/messages/"+messageId+"/attachments/"+id,options);
  var callOptions = {method:"GET"};
  var MessagePartBodyResource = CALL_(path,callOptions);
  return MessagePartBodyResource;
}

/**
* Immediately and permanently deletes the specified thread. This operation cannot be undone. Prefer threads.trash instead.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {string} id ID of the Thread to delete.
* @param {object} options Keypair of all optional parameters for this call
*/
function usersThreadsDelete(userId,id,options){
  var path = buildUrl_(""+userId+"/threads/"+id,options);
  var callOptions = {method:"DELETE"};
  var removeResource = CALL_(path,callOptions);
  return removeResource;
}

/**
* Gets the specified thread.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {string} id The ID of the thread to retrieve.
* @param {object} options Keypair of all optional parameters for this call
* @return {object} The returned ThreadResource object
*/
function usersThreadsGet(userId,id,options){
  var path = buildUrl_(""+userId+"/threads/"+id,options);
  var callOptions = {method:"GET"};
  var ThreadResource = CALL_(path,callOptions);
  return ThreadResource;
}

/**
* Lists the threads in the user's mailbox.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {object} options Keypair of all optional parameters for this call
* @return {object} The returned ListThreadsResponseResource object
*/
function usersThreadsList(userId,options){
  var path = buildUrl_(""+userId+"/threads",options);
  var callOptions = {method:"GET"};
  var ListThreadsResponseItems = CALLPAGE_(path,callOptions,"items");
  return ListThreadsResponseItems;
}

/**
* Modifies the labels applied to the thread. This applies to all messages in the thread.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {string} id The ID of the thread to modify.
* @param {object} ModifyThreadRequestResource An object containing the ModifyThreadRequestResource for this method
* @param {object} options Keypair of all optional parameters for this call
* @return {object} The returned ThreadResource object
*/
function usersThreadsModify(userId,id,ModifyThreadRequestResource,options){
  var path = buildUrl_(""+userId+"/threads/"+id+"/modify",options);
  var callOptions = {method:"POST",payload:JSON.stringify(ModifyThreadRequestResource)};
  var ThreadResource = CALL_(path,callOptions);
  return ThreadResource;
}

/**
* Moves the specified thread to the trash.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {string} id The ID of the thread to Trash.
* @param {object} options Keypair of all optional parameters for this call
* @return {object} The returned ThreadResource object
*/
function usersThreadsTrash(userId,id,options){
  var path = buildUrl_(""+userId+"/threads/"+id+"/trash",options);
  var callOptions = {method:"POST"};
  var ThreadResource = CALL_(path,callOptions);
  return ThreadResource;
}

/**
* Removes the specified thread from the trash.
*
* @param {string} userId The user's email address. The special value me can be used to indicate the authenticated user.
* @param {string} id The ID of the thread to remove from Trash.
* @param {object} options Keypair of all optional parameters for this call
* @return {object} The returned ThreadResource object
*/
function usersThreadsUntrash(userId,id,options){
  var path = buildUrl_(""+userId+"/threads/"+id+"/untrash",options);
  var callOptions = {method:"POST"};
  var ThreadResource = CALL_(path,callOptions);
  return ThreadResource;
}