How to use the Google Email Settings API and the OAuth2 for Apps Script Library to set email signatures for users in a Google Apps domain

Employee

This is my first time using the "Answer your own question" feature. I hope I'm doing this right. My Title triggered a warning that my question looks subjective and will probably be deleted.

I searched the site and didn't find any questions that matched the level of detail that I put into my response below, so I'm just trying to help out some fellow programmers by posting this.



As the administrator of a Google Apps domain, how do you use the Google Email Settings API with OAuth 2 to programmatically set the email signatures of users on your domain in Google Apps Script?

Employee

I experienced some confusion when trying to get this to work after OAuth 1 was deprecated, but with some help from awesome SO users, I was able to figure out a working solution.

First, you need to follow the steps to add this library to your Apps Script project:

https://github.com/googlesamples/apps-script-oauth2

After you have that set up, you can use their library to create an OAuth 2 service that is needed when calling the Email Settings API. Here is my working code:

function beginNewEmployeeProcedures() {

  var emailSettingsOauth2Service = createOauth2Service(‘Email Settings API’,’https://apps-apis.google.com/a/feeds/emailsettings/2.0/’,’authCallbackForEmailSettingsApi’);
  if (!emailSettingsOauth2Service.hasAccess()) { startOauth2AuthFlow(‘Email Settings API’,emailSettingsOauth2Service); return; }

  setSignature(emailSettingsOauth2Service,’[email protected]’,’cool email signature’);

}

function setSignature(service,email,signature) {

  try {

    var username = email.split(“@”)[0];

    var xml = '<?xml version="1.0" encoding="utf-8"?>' +
      '<atom:entry xmlns:atom="http://www.w3.org/2005/Atom" xmlns:apps="http://schemas.google.com/apps/2006" >' +
      '<apps:property name="signature" value="'+ signature +'" /></atom:entry>';

    var fetchArgs = {};
    fetchArgs.headers = {‘Authorization': ‘Bearer ‘+ service.getAccessToken()};
    fetchArgs.method = “PUT”;
    fetchArgs.contentType = “application/atom+xml”;
    fetchArgs.payload = xml;
    fetchArgs.muteHttpExceptions = true;

    var url = ‘https://apps-apis.google.com/a/feeds/emailsettings/2.0/yourgoogleappsdomain.com/’ + username + ‘/signature';

    UrlFetchApp.fetch(url, fetchArgs);

  } catch(e) {

    // failure notification email, etc

  }

}

function createOauth2Service(serviceName,scope,callbackFunctionName) {

  // Create a new service with the given name. The name will be used when
  // persisting the authorized token, so ensure it is unique within the
  // scope of the property store.
  var service = OAuth2.createService(serviceName)

  // Set the endpoint URLs, which are the same for all Google services.
  .setAuthorizationBaseUrl(‘https://accounts.google.com/o/oauth2/auth’)
  .setTokenUrl(‘https://accounts.google.com/o/oauth2/token’)

  // Set the client ID and secret, from the Google Developers Console.
  .setClientId(OAUTH2_CLIENT_ID)
  .setClientSecret(OAUTH2_CLIENT_SECRET)

  // Set the project key of the script using this library.
  .setProjectKey(OAUTH2_PROJECT_KEY)

  // Set the name of the callback function in the script referenced
  // above that should be invoked to complete the OAuth flow.
  .setCallbackFunction(callbackFunctionName)

  // Set the property store where authorized tokens should be persisted.
  .setPropertyStore(PropertiesService.getUserProperties())

  // Set the scopes to request (space-separated for Google services).
  .setScope(scope)

  // Below are Google-specific OAuth2 parameters.

  // Sets the login hint, which will prevent the account chooser screen
  // from being shown to users logged in with multiple accounts.
  .setParam(‘login_hint’, Session.getActiveUser().getEmail())

  // Requests offline access.
  .setParam(‘access_type’, ‘offline’)

  // Forces the approval prompt every time. This is useful for testing,
  // but not desirable in a production application.
  .setParam(‘approval_prompt’, ‘force’);

  return service;

}

function startOauth2AuthFlow(serviceName,service) {

  var authorizationUrl = service.getAuthorizationUrl();

  var template = HtmlService.createTemplate(
  ‘<a href="” target=”_blank”>’+
  ‘Click here to authorize this script to access the ‘ + serviceName + ‘‘ +
  ‘After closing the other tab, click the X in this window and start the script again.’);

  template.authorizationUrl = authorizationUrl;

  var page = template.evaluate();

  SpreadsheetApp.getUi().showModalDialog(page, ‘API Authorization’);

}

function authCallbackForEmailSettingsApi(request) {

  // this script is called by the auth screen when the user clicks the blue Accept button

  var oauth2Service = createOauth2Service(‘Email Settings API’,’https://apps-apis.google.com/a/feeds/emailsettings/2.0/’,’authCallbackForEmailSettingsApi’);

  var isAuthorized = oauth2Service.handleCallback(request);

  if (isAuthorized) {
    return HtmlService.createHtmlOutput(‘Success! You can close this tab.’);
  } else {
    return HtmlService.createHtmlOutput(‘Didn\’t work.’);
  }

}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Google Apps Email Settings API - Audit Log

From Dev

Exceeded maximum execution time in Google Apps Script to retrieve users name and email address from email domain

From Dev

Set email signature using Google Apps Script with Gmail API

From Dev

Google Apps Script for Forms: Want to send users specific number on email

From Dev

Is it possible to know if a domain is using Google Apps for email?

From Dev

How can I use a service account to get the email of a user in a Google Apps domain, without already knowing an email from that domain?

From Dev

How can I add an email alias to a domain alias in Google Apps?

From Dev

Google Apps Email Settings API and oauth2.0 Credential with service account

From Dev

Send email using GMail API in Google Apps Script

From Dev

Email address selector in Google Apps script

From Dev

How to authenticate with Google Email Settings API using service account oauth2 Python client?

From Dev

How to send a draft email using google apps script

From Dev

How to trigger a Google Apps Script once an email get in the inbox?

From Dev

How to avoid users seeing code in a Google apps script library

From Dev

How to use the Google Apps Script code for creating a Draft email (from 985)?

From Dev

Using Google Apps script, how to check if an email has a pdf attached to it, then forward it to another email address?

From Dev

Has Google lowered the email limits for Google Apps Script?

From Dev

Run script when new email arrives on gmail with Google apps script

From Dev

Using oAuth2 to send requests to Google Apps Script (i.e. GAS as google API)

From Dev

How to use OAuth 2.0 with a Google Apps Script library, with a static redirect URL?

From Dev

Is there a way to change the display name in email sent via Google Apps Script?

From Dev

Google Apps Script: Send PDF instead of .zip file in email

From Dev

Email a reminder based on the status of a cell Google apps script

From Dev

Google Apps Script - Send email based on data in cell

From Dev

Ignoring blank email address input field Google Apps Script

From Dev

Use Adwords API (MccApp) in Google Apps Script

From Dev

How to format text (bold, italics) in a Gmail email sent via Google Apps Script?

From Dev

How to automatically display a user email in an HTML form field using Google Apps Script and JavaScript

From Dev

How to obtain a list of users using weak passwords in a Google Apps domain

Related Related

  1. 1

    Google Apps Email Settings API - Audit Log

  2. 2

    Exceeded maximum execution time in Google Apps Script to retrieve users name and email address from email domain

  3. 3

    Set email signature using Google Apps Script with Gmail API

  4. 4

    Google Apps Script for Forms: Want to send users specific number on email

  5. 5

    Is it possible to know if a domain is using Google Apps for email?

  6. 6

    How can I use a service account to get the email of a user in a Google Apps domain, without already knowing an email from that domain?

  7. 7

    How can I add an email alias to a domain alias in Google Apps?

  8. 8

    Google Apps Email Settings API and oauth2.0 Credential with service account

  9. 9

    Send email using GMail API in Google Apps Script

  10. 10

    Email address selector in Google Apps script

  11. 11

    How to authenticate with Google Email Settings API using service account oauth2 Python client?

  12. 12

    How to send a draft email using google apps script

  13. 13

    How to trigger a Google Apps Script once an email get in the inbox?

  14. 14

    How to avoid users seeing code in a Google apps script library

  15. 15

    How to use the Google Apps Script code for creating a Draft email (from 985)?

  16. 16

    Using Google Apps script, how to check if an email has a pdf attached to it, then forward it to another email address?

  17. 17

    Has Google lowered the email limits for Google Apps Script?

  18. 18

    Run script when new email arrives on gmail with Google apps script

  19. 19

    Using oAuth2 to send requests to Google Apps Script (i.e. GAS as google API)

  20. 20

    How to use OAuth 2.0 with a Google Apps Script library, with a static redirect URL?

  21. 21

    Is there a way to change the display name in email sent via Google Apps Script?

  22. 22

    Google Apps Script: Send PDF instead of .zip file in email

  23. 23

    Email a reminder based on the status of a cell Google apps script

  24. 24

    Google Apps Script - Send email based on data in cell

  25. 25

    Ignoring blank email address input field Google Apps Script

  26. 26

    Use Adwords API (MccApp) in Google Apps Script

  27. 27

    How to format text (bold, italics) in a Gmail email sent via Google Apps Script?

  28. 28

    How to automatically display a user email in an HTML form field using Google Apps Script and JavaScript

  29. 29

    How to obtain a list of users using weak passwords in a Google Apps domain

HotTag

Archive