2017-04-24 1 views
0

Ich bin mir sicher, dass es etwas Einfaches gibt, dass ich hier vermisse, aber ich bin seit über einer Woche dabei. & kann es nicht herausfinden, also frage ich. Ich werde meine Frage mit Ich bin kein richtiger Programmierer! Ich bin ein Netzwerk-/Systemadministrator, der mithilfe von Google Apps Script Signaturen für alle Nutzer in unserer G Suite-Domain konfigurieren muss. Ich hatte ein gutes Stück Bash/Command Line/PowerShell Erfahrung, aber wenn es um "echte" Programmiersprachen geht, weiß ich ziemlich nichts.Verwenden von Google Apps Script zum Festlegen der E-Mail-Signaturen von Domänenbenutzern

Das sagte ich war auf einer anderen SO-Seite hier How to use the Gmail API, OAuth2 for Apps Script, and Domain-Wide Delegation to set email signatures for users in a G Suite domain über, wie Sie E-Mail-Signaturen zu lesen. Als ich das Skript zum ersten Mal ausprobierte, konnte ich es überhaupt nicht zum Laufen bringen. Ich habe es geändert & verwaltet, um es jetzt zu authentifizieren bekommen, aber nichts passiert, wenn es zu dem Teil kommt, wo es die Signaturen gesetzt werden sollte, scheint es nur zu beenden & das ist es! Hier ist mein modifizierter Code abzüglich aller privaten Bits:

// Adapted from script at https://stackoverflow.com/questions/40936257/how-to-use-the-gmail-api-oauth2-for-apps-script-and-domain-wide-delegation-to 

// 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_MY_KEY_GOES_HERE_\n-----END PRIVATE KEY-----\n'; 
var OAUTH2_SERVICE_ACCOUNT_CLIENT_EMAIL = '[email protected]erviceaccount.com'; 

function setSignatureTest() { 
    var email = '[email protected]'; 
    var signature = 'my test signature'; 
    var test = setSignature(email, signature); 
    Logger.log('test result: ' + test); 
} 

function setSignature(email, signature) { 
    Logger.log('starting setSignature'); 
    var signatureSetSuccessfully = false; 
    var service = getDomainWideDelegationService('Gmail: ', 'https://www.googleapis.com/auth/gmail.settings.basic', OAUTH2_SERVICE_ACCOUNT_CLIENT_EMAIL); 
    if (!service.hasAccess()) { 
    Logger.log('failed to authenticate as user ' + OAUTH2_SERVICE_ACCOUNT_CLIENT_EMAIL); 
    Logger.log(service.getLastError()); 
    signatureSetSuccessfully = service.getLastError(); 
    return signatureSetSuccessfully; 
    } else Logger.log('successfully authenticated as user ' + OAUTH2_SERVICE_ACCOUNT_CLIENT_EMAIL); 
    var resource = { 'sendAsEmail' : email, 'userId' : OAUTH2_SERVICE_ACCOUNT_CLIENT_EMAIL, 'signature' : signature }; 
    var options = 
     { 
     'method' : 'put', 
     'contentType' : 'application/json', 
     'Authorization' : 'Bearer ' + service.getAccessToken(), 
     'payload' : resource 
     }; 
    var emailForUrl = encodeURIComponent(email); 
    var url = 'https://www.googleapis.com/gmail/v1/users/me/settings/sendAs/' + emailForUrl; 
    var maxSetSignatureAttempts  = 1; 
    var currentSetSignatureAttempts = 0; 
    do { 
    try { 
     currentSetSignatureAttempts++; 
     Logger.log('currentSetSignatureAttempts: ' + currentSetSignatureAttempts); 
     var setSignatureResponse = UrlFetchApp.fetch(url, JSON.stringify(options)); 
     Logger.log('setSignatureResponse on successful attempt:' + setSignatureResponse); 
     signatureSetSuccessfully = true; 
     break; 
    } catch(e) { 
     Logger.log('set signature failed attempt, waiting 3 seconds and re-trying'); 
     Utilities.sleep(3000); 
    } 
    if (currentSetSignatureAttempts >= maxSetSignatureAttempts) { 
     Logger.log('exceeded ' + maxSetSignatureAttempts + ' set signature attempts, deleting user and ending script'); 
     Logger.log('URL: ' + url); 
     Logger.log('Value of JSON.stringify(options):' + JSON.stringify(options)); 
     Logger.log('Value of setSignatureResponse:' + setSignatureResponse); 
     throw new Error('Something went wrong when setting their email signature.'); 
    } 
    } while (!signatureSetSuccessfully); 
    return signatureSetSuccessfully; 
} 

function getDomainWideDelegationService(serviceName, scope, OAUTH2_SERVICE_ACCOUNT_CLIENT_EMAIL) { 
    Logger.log('starting getDomainWideDelegationService for email: ' + OAUTH2_SERVICE_ACCOUNT_CLIENT_EMAIL); 
    return OAuth2.createService(serviceName + OAUTH2_SERVICE_ACCOUNT_CLIENT_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(OAUTH2_SERVICE_ACCOUNT_CLIENT_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); 
} 

Wer hat irgendwelche Ideen dazu? Ich bin sicher, jemand anderes hat das schon gemacht & Ich mache irgendwo einen einfachen Fehler. Ich habe das Gefühl, dass das Problem in meinen Payload-Optionen liegt, aber ich bin mir wirklich nicht sicher, wie ich das beheben kann. & alles, was ich versuche, tut nichts.

Edit: Bitte sehen Sie unten für sanitized Log-Ausgabe.

[17-04-24 18:24:27:087 PDT] starting setSignature 
[17-04-24 18:24:27:088 PDT] starting getDomainWideDelegationService for email: [email protected]serviceaccount.com 
[17-04-24 18:24:27:521 PDT] successfully authenticated as user [email protected]serviceaccount.com 
[17-04-24 18:24:27:550 PDT] currentSetSignatureAttempts: 1 
[17-04-24 18:24:27:552 PDT] set signature failed attempt, waiting 3 seconds and re-trying 
[17-04-24 18:24:30:554 PDT] exceeded 1 set signature attempts, deleting user and ending script 
[17-04-24 18:24:30:554 PDT] URL: https://www.googleapis.com/gmail/v1/users/me/settings/sendAs/user%40domain.com 
[17-04-24 18:24:30:555 PDT] Value of JSON.stringify(options):{"method":"put","contentType":"application/json","Authorization":"Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”,”payload":{"sendAsEmail”:”[email protected]”,”userId":"[email protected]serviceaccount.com","signature":"my test signature"}} 
[17-04-24 18:24:30:556 PDT] Value of setSignatureResponse:undefined 

Protokollausgabe nach Änderungen 2017.04.25.16:00:

[17-04-25 12:37:00:260 PDT] starting setSignature 
[17-04-25 12:37:00:261 PDT] starting getDomainWideDelegationService for email: [email protected]serviceaccount.com 
[17-04-25 12:37:00:278 PDT] successfully authenticated as user [email protected]serviceaccount.com 
[17-04-25 12:37:00:289 PDT] currentSetSignatureAttempts: 1 
[17-04-25 12:37:00:343 PDT] setSignatureResponse on successful attempt:{ 
"error": { 
    "errors": [ 
    { 
    "domain": "global", 
    "reason": "failedPrecondition", 
    "message": "Bad Request" 
    } 
    ], 
    "code": 400, 
    "message": "Bad Request" 
} 
} 

[17-04-25 12:37:00:343 PDT] test result: true 
+1

Was ist Ihre Log oder Ausführungs Transkript sagen? (View> Logs/Execution Transcript) –

+0

Bitte beachten Sie die Bearbeitung, die ich gerade gemacht habe, danke Jack! – user7916051

+0

Sie müssen dies in eine gültige ID 'var email = '[email protected]' ändern;' vielleicht Ihre ID, um sicherzustellen, dass es Ihre Signatur ändert –

Antwort

0

Die Ermächtigung in die Request-Header gehen muss wie so

var options = 
     { 
     'headers' : {'Authorization' : 'Bearer ' + service.getAccessToken()}, 
     'method' : 'put', 
     'contentType' : 'application/json', 
     'payload' : JSON.stringify(resource) 
     }; 

Schließlich Ihr Aufruf an die API sieht so aus:

var setSignatureResponse = UrlFetchApp.fetch(url, options); 

Hoffnung, dass das Problem

+0

Das hat mich viel näher gebracht! Ich bin nun in der Lage, ein paar nützliche Rückmeldungen in den Protokollen zu sehen, nachdem ich Ihre vorgeschlagenen Änderungen vorgenommen und auch ''muteHttpExceptions': true;' zu meinen Optionen hinzugefügt habe. Ich hoffe, dass ich den Rest herausfinden kann, nachdem ich die API-Dokumentation von Google gelesen habe. Ich füge die aktuelle Protokollausgabe an meine ursprüngliche Frage an. – user7916051

0

Try contenType-ctAPPLICATION_JSON löst sich ändern:

"contentType": "ctAPPLICATION_JSON", 
Verwandte Themen