1

這是我發佈的前一個問題/回答(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)的後續操作,但我正在創建一個新問題,因爲Email Settings API已被棄用,現在過程顯着不同。如何使用Gmail API,適用於Apps腳本的OAuth2和域範圍委派爲G Suite網域中的用戶設置電子郵件簽名

作爲G Suite域的管理員,您如何使用Gmail API以編程方式通過Google Apps腳本設置您域中用戶的電子郵件簽名?

回答

2

此方法使用Gmail API,用於Apps腳本庫的OAuth2和「域範圍授權」,這是G Suite管理員代表其域中的用戶進行API調用的方式。

步驟1:確保OAuth2 For Apps Script庫已添加到您的項目中。

第2步:設置「域範圍授權」。有一個頁面here解釋瞭如何爲Drive API執行此操作,但對於任何Google API(包括Gmail API)來說都幾乎相同。遵循該頁面上的步驟,直至包括「代表服務帳戶的全域授權」步驟。

步驟3:下面的代碼包括如何設置簽名前面的步驟都完成後:

function setSignatureTest() { 

    var email = '[email protected]'; 

    var signature = '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', 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 username = email.split("@")[0]; 

    var resource = { signature: signature }; 

    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; 

    var maxSetSignatureAttempts  = 20; 
    var currentSetSignatureAttempts = 0; 

    do { 

    try { 

     currentSetSignatureAttempts++; 

     Logger.log('currentSetSignatureAttempts: ' + currentSetSignatureAttempts); 

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

     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'); 

     throw new Error('Something went wrong when setting their email signature.'); 

    } 

    } while (!signatureSetSuccessfully); 

    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-----\nxxxxxxxxxxxxxxxxxxxxx\n-----END PRIVATE KEY-----\n'; 
var OAUTH2_SERVICE_ACCOUNT_CLIENT_EMAIL = 'xxxxxxxxxxxxxxxxxxxxx.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); 

} 

請注意:do-while循環與maxSetSignatureAttemptscurrentSetSignatureAttempts變量是沒有必要的。我添加了它,因爲如果您在創建Google帳戶並分配G Suite許可證後立即嘗試設置簽名,則有時Gmail API會返回錯誤,就好像用戶尚未創建一樣。該do-while循環基本上等待3秒鐘,如果出現錯誤,則再次嘗試,最多x次。如果您爲現有用戶設置簽名,則不應出現該問題。此外,最初我只是有一個固定的10秒睡眠,但大部分時間不需要很長時間,但有些時候它仍然會失敗。所以這個循環比固定的睡眠量更好。

+0

嗨,這可以做,而不是一個G Suite域的管理員?我只想登錄到我的gmail帳戶以發出http請求... –

+0

不,您不能這樣做,因爲「域範圍委派」專門用於G Suite管理員。但是,如果您只是嘗試設置自己的電子郵件簽名,則無需使用DWD即可完成此操作。擺脫對「getDomainWideDelegationService」和第一個「if」語句的調用,並將'service.getAccessToken()'改爲'ScriptApp.getOAuthToken()'。這應該爲您自己的帳戶獲得有效的令牌。讓我知道這是否有效。 – mike

+0

是的,工作!謝謝 –

相關問題