Skip to content

Instantly share code, notes, and snippets.

@mkornatz
Created December 4, 2017 15:05
Show Gist options
  • Save mkornatz/f3203f7ae71b6255fc8bbc7065aed2d5 to your computer and use it in GitHub Desktop.
Save mkornatz/f3203f7ae71b6255fc8bbc7065aed2d5 to your computer and use it in GitHub Desktop.

Revisions

  1. mkornatz created this gist Dec 4, 2017.
    114 changes: 114 additions & 0 deletions update-emails.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,114 @@
    /**
    * Set email signature on provided email addresses
    * To ensure signatures have been successfully updated, follow the steps below:
    *
    * 1. Add comma-separated email addresses (example: '[email protected]', '[email protected]', '[email protected]')
    * 2. Navigate to Run > setAllSignatures
    * 3. Navigate to View > Logs
    * 4. View log output "Signature successfully updated for [email address]"
    */
    function setAllSignatures() {
    var signatureTemplate = getTemplate('Signature');

    var allSignatures = [
    '[email protected]'
    ];

    if (allSignatures.length > 0) {
    for(var i in allSignatures) {
    setSignature(allSignatures[i], signatureTemplate);
    }
    } else {
    Logger.log("Oops, you need to specify an email address");
    }
    }

    /**
    *
    *
    *
    *
    *
    * Helper Functions (below) - Do Not Run
    *
    *
    *
    *
    *
    */

    /**
    * Get the proper authorization from service account
    * More information on service account at https://console.developers.google.com
    *
    * @param email {String} email address to be updated
    */
    function getOAuthService(email) {
    var OAUTH2_SERVICE_ACCOUNT_PRIVATE_KEY = '-----BEGIN PRIVATE KEY-----\nMIIE...=\n-----END PRIVATE KEY-----\n';
    var OAUTH2_SERVICE_ACCOUNT_CLIENT_EMAIL = 'email-signature-updater@email-signature-100000.iam.gserviceaccount.com';

    // service identifier needs to change per user
    return OAuth2.createService("Email Signature Updater - " + email)
    .setTokenUrl('https://accounts.google.com/o/oauth2/token')
    .setPrivateKey(OAUTH2_SERVICE_ACCOUNT_PRIVATE_KEY)
    .setIssuer(OAUTH2_SERVICE_ACCOUNT_CLIENT_EMAIL)
    .setSubject(email)
    .setPropertyStore(PropertiesService.getScriptProperties())
    .setScope('https://www.googleapis.com/auth/gmail.settings.basic')
    .setParam('access_type', 'offline');
    }

    /**
    * Reset the authorization state, so that it can be re-tested.
    */
    function resetService(email) {
    getOAuthService(email).reset();
    }

    /**
    * Get the contents of an HTML template
    *
    * @param name {String} Name of HTML file
    * @return {String} HTML string
    */
    function getTemplate(name) {
    return HtmlService.createHtmlOutputFromFile(name).getContent();
    }

    /**
    * Call out to Gmail API to set email signature on given address
    *
    * @param userEmail {String} email address to be updated
    * @param signature {String} HTML string used for signature template
    */
    function setSignature(userEmail, signature) {
    // Reset the service so we can reuse it
    resetService(userEmail);

    var params = {signature: signature},
    service = getOAuthService(userEmail),
    url = 'https://content.googleapis.com/gmail/v1/users/' + encodeURIComponent(userEmail) + '/settings/sendAs/' + encodeURIComponent(userEmail) + '?alt=json';

    if (service.hasAccess()) {
    var response = UrlFetchApp.fetch(url, {
    method: 'PATCH',
    muteHttpExceptions: true,
    contentType: 'application/json',
    payload: JSON.stringify(params),
    headers: {
    'Authorization': 'Bearer ' + service.getAccessToken()
    }
    });

    // error handling
    if (response.getResponseCode() !== 200) {
    Logger.log("ERROR: " + response.getContentText());
    } else {
    Logger.log("Signature successfully updated for " + userEmail + "!");
    }

    } else {
    Logger.log(service.getLastError());
    }

    }