问题描述
这是我之前发布的问题/答案的后续(如何使用 Google 电子邮件设置 API 和 OAuth2 for Apps 脚本库为 Google Apps 域中的用户设置电子邮件签名),但我正在创建一个新问题,因为 电子邮件设置 API已被弃用,现在流程有很大不同.
This is a follow-up to a previous question/answer I posted (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), but I'm creating a new question since the Email Settings API has been deprecated and the process is significantly different now.
作为 G Suite 域的管理员,您如何使用 Gmail API 以编程方式通过 Google Apps 脚本设置您域中用户的电子邮件签名?
As the administrator of a G Suite domain, how do you use the Gmail API to programmatically set the email signatures of users in your domain through Google Apps Script?
推荐答案
此方法使用 Gmail API、OAuth2 for Apps 脚本库和域范围的授权",这是 G Suite 管理员的一种方式代表其域内的用户进行 API 调用.
This method uses the Gmail API, the OAuth2 for Apps Script library, and "Domain-wide Delegation of Authority", which is a way for G Suite admins to make API calls on behalf of users within their domain.
第 1 步:确保 OAuth2 For Apps 脚本 库已添加到您的项目中.
Step 1: Make sure the OAuth2 For Apps Script library is added to your project.
第 2 步: 设置域范围的授权".有一个页面 here 解释了如何为 Drive API 执行此操作,但它很漂亮对于任何 Google API,包括 Gmail API,都大致相同.按照该页面上的步骤直到并包括将域范围的权限委派给您的服务帐户"步骤.
Step 2: Set up "Domain-Wide Delegation of Authority." There's a page here explaining how to do it for the Drive API, but it's pretty much the same for any Google API, including the Gmail API. Follow the steps on that page up to, and including, the "Delegate domain-wide authority to your service account" step.
第3步:下面的代码包括在前面的步骤完成后如何设置签名:
Step 3: The code below includes how to set the signature after the previous steps are complete:
function setSignatureTest() {
var email = 'test@test.com';
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-----
xxxxxxxxxxxxxxxxxxxxx
-----END PRIVATE KEY-----
';
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);
}
请注意:带有 maxSetSignatureAttempts
和 currentSetSignatureAttempts
变量的 do-while 循环不是必需的.我添加它是因为如果您在创建 Google 帐户并分配 G Suite 许可证后立即尝试设置签名,有时 Gmail API 会返回一个错误,就好像用户尚未创建一样.如果出现错误,do-while 循环基本上会等待 3 秒,然后再试一次,最多 x 次.如果您为现有用户设置签名,则不应该有这个问题.另外,原本我只是有一个固定的10秒睡眠,但大部分时间不需要那么长时间,但其他时候它仍然会失败.所以这个循环比固定的睡眠量要好.
Please note: the do-while loop with the maxSetSignatureAttempts
and currentSetSignatureAttempts
variables is not necessary. I added it because if you're trying to set signatures immediately after creating the Google account and assigning a G Suite license, sometimes the Gmail API returns an error as if the user wasn't created yet. That do-while loop basically waits 3 seconds if it gets an error, then tries again, up to x number of times. You shouldn't have that issue if you're setting signatures for existing users. Also, originally I just had a fixed 10-second sleep, but most of the time it didn't need to take that long, but other times it would still fail. So this loop is better than a fixed sleep amount.
这篇关于如何使用 Gmail API、OAuth2 for Apps 脚本和域范围委派为 G Suite 域中的用户设置电子邮件签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!