Skip to main content
 首页 » 编程设计

google-apps-script之如何使用 Google 电子邮件设置 API 和 OAuth2 for Apps 脚本库为 Google Apps 域中的用户设置电子邮件签名

2024年12月31日9exmyth

这是我第一次使用“回答你自己的问题”功能。我希望我做得对。我的标题触发了一个警告,称我的问题看起来很主观,可能会被删除。

我搜索了该网站,没有找到任何与我在下面的回复中输入的详细程度相匹配的问题,因此我只是想通过发布此内容来帮助一些程序员同行。



作为 Google Apps 域的管理员,您如何使用 Google Email Settings APIOAuth 2在 Google Apps 脚本中以编程方式设置您域中用户的电子邮件签名?

请您参考如下方法:

OAuth 1 was deprecated 之后尝试让它工作时,我遇到了一些困惑。 ,但是在出色的 SO 用户的帮助下,我找到了一个可行的解决方案。

首先,您需要按照以下步骤将此库添加到您的 Apps 脚本项目中:

https://github.com/googlesamples/apps-script-oauth2

完成设置后,您可以使用他们的库创建调用电子邮件设置 API 时所需的 OAuth 2 服务。这是我的工作代码:

function beginNewEmployeeProcedures() { 
 
  var emailSettingsOauth2Service = createOauth2Service(‘Email Settings API’,’https://apps-apis.google.com/a/feeds/emailsettings/2.0/’,’authCallbackForEmailSettingsApi’); 
  if (!emailSettingsOauth2Service.hasAccess()) { startOauth2AuthFlow(‘Email Settings API’,emailSettingsOauth2Service); return; } 
 
  setSignature(emailSettingsOauth2Service,’<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1e6a7b6d6a5e67716b6c79717179727b7f6e6e6d7a71737f7770307d7173" rel="noreferrer noopener nofollow">[email protected]</a>’,’cool email signature’); 
 
} 
 
function setSignature(service,email,signature) { 
 
  try { 
 
    var username = email.split(“@”)[0]; 
 
    var xml = '<?xml version="1.0" encoding="utf-8"?>' + 
      '<atom:entry xmlns:atom="http://www.w3.org/2005/Atom" xmlns:apps="http://schemas.google.com/apps/2006" >' + 
      '<apps:property name="signature" value="'+ signature +'" /></atom:entry>'; 
 
    var fetchArgs = {}; 
    fetchArgs.headers = {‘Authorization': ‘Bearer ‘+ service.getAccessToken()}; 
    fetchArgs.method = “PUT”; 
    fetchArgs.contentType = “application/atom+xml”; 
    fetchArgs.payload = xml; 
    fetchArgs.muteHttpExceptions = true; 
 
    var url = ‘https://apps-apis.google.com/a/feeds/emailsettings/2.0/yourgoogleappsdomain.com/’ + username + ‘/signature'; 
 
    UrlFetchApp.fetch(url, fetchArgs); 
 
  } catch(e) { 
 
    // failure notification email, etc 
 
  } 
 
} 
 
function createOauth2Service(serviceName,scope,callbackFunctionName) { 
 
  // Create a new service with the given name. The name will be used when 
  // persisting the authorized token, so ensure it is unique within the 
  // scope of the property store. 
  var service = OAuth2.createService(serviceName) 
 
  // Set the endpoint URLs, which are the same for all Google services. 
  .setAuthorizationBaseUrl(‘https://accounts.google.com/o/oauth2/auth’) 
  .setTokenUrl(‘https://accounts.google.com/o/oauth2/token’) 
 
  // Set the client ID and secret, from the Google Developers Console. 
  .setClientId(OAUTH2_CLIENT_ID) 
  .setClientSecret(OAUTH2_CLIENT_SECRET) 
 
  // Set the project key of the script using this library. 
  .setProjectKey(OAUTH2_PROJECT_KEY) 
 
  // Set the name of the callback function in the script referenced 
  // above that should be invoked to complete the OAuth flow. 
  .setCallbackFunction(callbackFunctionName) 
 
  // Set the property store where authorized tokens should be persisted. 
  .setPropertyStore(PropertiesService.getUserProperties()) 
 
  // Set the scopes to request (space-separated for Google services). 
  .setScope(scope) 
 
  // Below are Google-specific OAuth2 parameters. 
 
  // Sets the login hint, which will prevent the account chooser screen 
  // from being shown to users logged in with multiple accounts. 
  .setParam(‘login_hint’, Session.getActiveUser().getEmail()) 
 
  // Requests offline access. 
  .setParam(‘access_type’, ‘offline’) 
 
  // Forces the approval prompt every time. This is useful for testing, 
  // but not desirable in a production application. 
  .setParam(‘approval_prompt’, ‘force’); 
 
  return service; 
 
} 
 
function startOauth2AuthFlow(serviceName,service) { 
 
  var authorizationUrl = service.getAuthorizationUrl(); 
 
  var template = HtmlService.createTemplate( 
  ‘<a href="” target=”_blank”>’+ 
  ‘Click here to authorize this script to access the ‘ + serviceName + ‘‘ + 
  ‘After closing the other tab, click the X in this window and start the script again.’); 
 
  template.authorizationUrl = authorizationUrl; 
 
  var page = template.evaluate(); 
 
  SpreadsheetApp.getUi().showModalDialog(page, ‘API Authorization’); 
 
} 
 
function authCallbackForEmailSettingsApi(request) { 
 
  // this script is called by the auth screen when the user clicks the blue Accept button 
 
  var oauth2Service = createOauth2Service(‘Email Settings API’,’https://apps-apis.google.com/a/feeds/emailsettings/2.0/’,’authCallbackForEmailSettingsApi’); 
 
  var isAuthorized = oauth2Service.handleCallback(request); 
 
  if (isAuthorized) { 
    return HtmlService.createHtmlOutput(‘Success! You can close this tab.’); 
  } else { 
    return HtmlService.createHtmlOutput(‘Didn\’t work.’); 
  } 
 
}