0

Это мой первый опыт использования функции «Ответьте на свой вопрос». Надеюсь, я сделаю это правильно. Мой заголовок вызвал предупреждение о том, что мой вопрос выглядит субъективным и, вероятно, будет удален.Как использовать API настроек электронной почты Google и библиотеку скриптов OAuth2 для приложений, чтобы устанавливать подписи электронной почты для пользователей в домене Google Apps.

Я искал сайт и не нашел вопросов, которые соответствовали уровню детализации, который я ввел в свой ответ ниже, поэтому я просто пытаюсь помочь некоторым программистам-программистам, разместив это.



Как администратор домена Служб Google, как использовать Google Email Settings API с OAuth 2 программно задать подписи электронной почты пользователей домена в Google Apps Script?

+0

API настроек электронной почты устарел и будет отклонен 7 июля 2017 года. Вместо этого Google рекомендует использовать API Gmail. Я опубликовал следующий вопрос, в котором объясняется, как использовать это [здесь] (http://stackoverflow.com/questions/40936257/how-to-use-the-gmail-api-oauth2-for-apps-script и-Общедоменный делегированию к/40936258 # 40936258). – mike

ответ

3

Я испытал некоторое замешательство, пытаясь заставить его работать после OAuth 1 was deprecated, но с некоторой помощью от огромных пользователей SO я смог найти рабочее решение.

Во-первых, вам необходимо следовать инструкциям, чтобы добавить эту библиотеку в ваш проект Apps Script:

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

После того, что настройки, вы можете использовать свою библиотеку, чтобы создать 2 сервиса OAuth, что требуется при вызове API настроек электронной почты. Вот мой рабочий код:

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,’[email protected]’,’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.’); 
    } 

} 
+1

Благодарим за обмен. OAuth всегда был одним из моих заклятых врагов. – ScampMichael

 Смежные вопросы

  • Нет связанных вопросов^_^