此方法使用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循環與maxSetSignatureAttempts
和currentSetSignatureAttempts
變量是沒有必要的。我添加了它,因爲如果您在創建Google帳戶並分配G Suite許可證後立即嘗試設置簽名,則有時Gmail API會返回錯誤,就好像用戶尚未創建一樣。該do-while循環基本上等待3秒鐘,如果出現錯誤,則再次嘗試,最多x次。如果您爲現有用戶設置簽名,則不應出現該問題。此外,最初我只是有一個固定的10秒睡眠,但大部分時間不需要很長時間,但有些時候它仍然會失敗。所以這個循環比固定的睡眠量更好。
嗨,這可以做,而不是一個G Suite域的管理員?我只想登錄到我的gmail帳戶以發出http請求... –
不,您不能這樣做,因爲「域範圍委派」專門用於G Suite管理員。但是,如果您只是嘗試設置自己的電子郵件簽名,則無需使用DWD即可完成此操作。擺脫對「getDomainWideDelegationService」和第一個「if」語句的調用,並將'service.getAccessToken()'改爲'ScriptApp.getOAuthToken()'。這應該爲您自己的帳戶獲得有效的令牌。讓我知道這是否有效。 – mike
是的,工作!謝謝 –