如何使用Google电子邮件设置API和OAuth2 for Apps脚本库为Google Apps域中的用户设置电子邮件签名 [英] 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

查看:226
本文介绍了如何使用Google电子邮件设置API和OAuth2 for Apps脚本库为Google Apps域中的用户设置电子邮件签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我搜索了该网站,但没有发现任何问题与我在下面给出的回复中详细说明的级别相匹配,所以我只是想通过发布来帮助一些程序员。









作为Google Apps网域的管理员,您如何使用 Google电子邮件设置API OAuth 2 以编程方式在Google Apps Script中设置您网域中用户的电子邮件签名?

>在 OAuth 1被弃用后尝试使其发挥作用时,我遇到了一些困惑,但有一些来自aweso的帮助我是SO用户,我能够找出一个可行的解决方案。



首先,您需要按照以下步骤将这个库添加到您的Apps Script项目中:



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



完成设置后,您可以使用其库创建调用Email Settings API时所需的OAuth 2服务。这里是我的工作代码:

pre $ 函数beginNewEmployeeProcedures(){

var emailSettingsOauth2Service = createOauth2Service('Email设置API','https://apps-apis.google.com/a/feeds/emailsettings/2.0/','authCallbackForEmailSettingsApi');
if(!emailSettingsOauth2Service.hasAccess()){startOauth2AuthFlow('Email Settings API',emailSettingsOauth2Service);返回; }

setSignature(emailSettingsOauth2Service,'test @ yourgoogleappsdomain.com','cool email signature');


$ b函数setSignature(服务,电子邮件,签名){

尝试{

var username = email。分裂(@)[0];

var xml ='<?xml version =1.0encoding =utf-8?>'+
'< atom:entry xmlns:atom =http: //www.w3.org/2005/Atomxmlns: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){

//故障通知电子邮件等

}

}

函数createOauth2Service(serviceName,scope,callbackFunctionName){

//使用给定名称创建一个新服务。该名称将在
//持久授权令牌时使用,因此请确保它在属性存储区的
//范围内是唯一的。
var service = OAuth2.createService(serviceName)

//设置所有Google服务的端点URL。
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')

//从Google Developers Console中设置客户端ID和密码。
.setClientId(OAUTH2_CLIENT_ID)
.setClientSecret(OAUTH2_CLIENT_SECRET)

//使用此库设置脚本的项目键。
.setProjectKey(OAUTH2_PROJECT_KEY)

//在引用
//的脚本中设置回调函数的名称,该脚本应该被调用以完成OAuth流程。
.setCallbackFunction(callbackFunctionName)

//设置应该保留授权令牌的属性存储区。
.setPropertyStore(PropertiesService.getUserProperties())

//将范围设置为请求(用于Google服务的空格分隔)。
.setScope(范围)

//以下是Google特定的OAuth2参数。

//设置登录提示,这将阻止帐户选择器屏幕
//显示给使用多个帐户登录的用户。
.setParam('login_hint',Session.getActiveUser()。getEmail())

//请求脱机访问。
.setParam('access_type','offline')

//每次强制批准提示。这对于测试
//很有用,但在生产应用程序中不可取。
.setParam('approval_prompt','force');

退货服务;



函数startOauth2AuthFlow(serviceName,service){

var authorizationUrl = service.getAuthorizationUrl();

var template = HtmlService.createTemplate(
'< a href =target =_ blank>'+
'点击此处授权此脚本访问'+ serviceName +''+
'在关闭另一个选项卡后,单击此窗口中的X并再次启动脚本。');

template.authorizationUrl = authorizationUrl;

var page = template.evaluate();

SpreadsheetApp.getUi()。showModalDialog(page,'API Authorization');

}

函数authCallbackForEmailSettingsApi(request){

//当用户点击蓝色的Accept按钮时,此脚本被auth屏幕调用

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('Succe ');
} else {
return HtmlService.createHtmlOutput('Didn'''t work。');
}

}


This is my first time using the "Answer your own question" feature. I hope I'm doing this right. My Title triggered a warning that my question looks subjective and will probably be deleted.

I searched the site and didn't find any questions that matched the level of detail that I put into my response below, so I'm just trying to help out some fellow programmers by posting this.



As the administrator of a Google Apps domain, how do you use the Google Email Settings API with OAuth 2 to programmatically set the email signatures of users on your domain in Google Apps Script?

解决方案

I experienced some confusion when trying to get this to work after OAuth 1 was deprecated, but with some help from awesome SO users, I was able to figure out a working solution.

First, you need to follow the steps to add this library to your Apps Script project:

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

After you have that set up, you can use their library to create an OAuth 2 service that is needed when calling the Email Settings API. Here is my working code:

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,’test@yourgoogleappsdomain.com’,’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.’);
  }

}

这篇关于如何使用Google电子邮件设置API和OAuth2 for Apps脚本库为Google Apps域中的用户设置电子邮件签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆