Last active
January 13, 2023 14:19
-
-
Save tholeb/c3775b7e747ea84fcc5febaa41872629 to your computer and use it in GitHub Desktop.
Gmail Signature using apps scripts, Gmail API and a G Suite Domain
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Original code : https://stackoverflow.com/a/40936258/11379030 | |
function setSignatureTest() { | |
var user = { | |
primaryEmail: "name@example.com", | |
name: { | |
fullName:'First Last', | |
familyName:'Last name', | |
givenName:'First name' | |
} | |
}; | |
var test = setSignature(user.primaryEmail, user); | |
Logger.log('test result: ' + test); | |
} | |
function listAllUsers() { | |
var pageToken; | |
var page; | |
do { | |
page = AdminDirectory.Users.list({ | |
domain: 'example.com', | |
orderBy: 'givenName', | |
maxResults: 500, | |
pageToken: pageToken | |
}); | |
var users = page.users; | |
var accountsToIgnore = [ | |
'test@example.com', | |
'testtest@example.com' | |
]; | |
if (users) { | |
for (var i = 0; i < users.length; i++) { | |
var user = users[i]; | |
if (accountsToIgnore.indexOf(user.primaryEmail) == -1) { | |
var userName = user.name.fullName; | |
var userEmail = user.primaryEmail; | |
var userOrgRole = user.organizations ? user.organizations[0].title : '' | |
Logger.log('-- %s (%s) %s', userName, userEmail, userOrgRole); | |
Logger.log('%s (%s)', user); | |
setSignature(userEmail, user); | |
} | |
} | |
} else { | |
Logger.log('No users found.'); | |
} | |
pageToken = page.nextPageToken; | |
} while (pageToken); | |
} | |
function setSignature(email, userData) { | |
var signatureSetSuccessfully = false; | |
var authorizationScope = ['https://www.googleapis.com/auth/gmail.settings.sharing','https://www.googleapis.com/auth/gmail.settings.basic']; | |
var service = getDomainWideDelegationService("Gmail: ", authorizationScope, email); | |
if (!service.hasAccess()) { | |
Logger.log("failed to authenticate as user " + email); | |
Logger.log(service.getLastError()); | |
signatureSetSuccessfully = service.getLastError(); | |
return signatureSetSuccessfully; | |
} else { | |
Logger.log("successfully authenticated as user " + email); | |
} | |
var signatureTemplate = HtmlService.createHtmlOutputFromFile("signature").getContent(); | |
var userSig = signatureTemplate | |
.replace(/(\r\n|\n|\r)/gm, "") | |
.replace(/{email}/g, userData.primaryEmail) | |
.replace(/{firstName}/g, userData.name.givenName) | |
.replace(/{lastName}/g, userData.name.familyName) | |
.replace(/{jobTitle}/g, userData.organizations ? userData.organizations[0].title : '') | |
var resource = { signature: userSig }; | |
var requestBody = {}; | |
requestBody.headers = {"Authorization": "Bearer " + service.getAccessToken()}; | |
requestBody.contentType = "application/json"; | |
requestBody.method = "PUT"; | |
requestBody.payload = JSON.stringify(resource); | |
requestBody.muteHttpExceptions = false; | |
var emailForUrl = encodeURIComponent(email); | |
var url = "https://www.googleapis.com/gmail/v1/users/me/settings/sendAs/" + emailForUrl; | |
try { | |
var setSignatureResponse = UrlFetchApp.fetch(url, requestBody); | |
signatureSetSuccessfully = true; | |
Logger.log("setSignatureResponse on successful attempt:" + JSON.parse(setSignatureResponse).sendAsEmail); | |
} catch (e) { | |
Logger.log("Set signature with HTTP request failed: " + e); | |
} | |
return signatureSetSuccessfully; | |
} | |
// these two things are included in the .JSON file that you download when creating the service account and service account key | |
var OAUTH2_SERVICE_ACCOUNT_PRIVATE_KEY = '-----BEGIN PRIVATE KEY-----\n\n-----END PRIVATE KEY-----\n'; | |
var OAUTH2_SERVICE_ACCOUNT_CLIENT_EMAIL = 'xxx@yyy.iam.gserviceaccount.com'; | |
function getDomainWideDelegationService(serviceName, scope, email) { | |
Logger.log('starting getDomainWideDelegationService for email: ' + email); | |
return OAuth2.createService(serviceName + email) | |
// Set the endpoint URL. | |
.setTokenUrl('https://accounts.google.com/o/oauth2/token') | |
// Set the private key and issuer. | |
.setPrivateKey(OAUTH2_SERVICE_ACCOUNT_PRIVATE_KEY) | |
.setIssuer(OAUTH2_SERVICE_ACCOUNT_CLIENT_EMAIL) | |
// Set the name of the user to impersonate. This will only work for | |
// Google Apps for Work/EDU accounts whose admin has setup domain-wide | |
// delegation: | |
// https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority | |
.setSubject(email) | |
// Set the property store where authorized tokens should be persisted. | |
.setPropertyStore(PropertiesService.getScriptProperties()) | |
// Set the scope. This must match one of the scopes configured during the | |
// setup of domain-wide delegation. | |
.setScope(scope); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
IT WORKS, thank you, I have a question... Is there a way to update a signature? It only works when I do not have any signature registered