创建一个自定义“from”作为GAS和API的别名发送 [英] Creates a custom "from" send-as alias with GAS and APIs

查看:188
本文介绍了创建一个自定义“from”作为GAS和API的别名发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我想在gmail设置中添加发送为参数。为我的所有用户,并将其更改为使默认帐户发送邮件。
我知道GUI很热,但我想用GAS做。
知道的代码是针对特定用户的测试。



Gmail API的参考资料

  var JSON = {
private_key:----- BEGIN PRIVATE KEY ----- \\ ---- ---- END PRIVATE KEY ----- \\\

client_email:client .. @ project-id-XXXXX.gserviceaccount.com,
client_id:12345800,
user_email:mainaccount @ dominio .com
};
$ b $ function getOAuthService(user){
return OAuth2.createService('Service Account')
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/ auth')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setPrivateKey(JSON.private_key)
.setIssuer(JSON.client_email)
.setSubject(JSON.user_email)
.setPropertyStore(PropertiesService.getScriptProperties())
.setParam('access_type','offline')
.setParam('approval_prompt', 'force')
.setScope('https://www.googleapis.com/auth/gmail.settings.sharing')
.setScope('https://www.googleapis.com/auth /gmail.settings.basic');
}

函数createAlias(){


var userEmail ='mainaccount@dominio.com';
var alias = {
别名:'makealiasdefault@dominio.com'
};
alias = AdminDirectory.Users.Aliases.insert(alias,userEmail);
Logger.log('为用户%s创建别名%s。',alias.alias,userEmail);

var service = getOAuthService();

service.reset();
if(service.hasAccess()){
var url ='https://www.googleapis.com/gmail/v1/users/'+userEmail+'/settings/sendAs'
var headers = {
Authorization:'Bearer'+ service.getAccessToken()
};

var options = {
'method':'post',
'headers':headers,
'method':'GET',
'muteHttpExceptions':true
};
var response = UrlFetchApp.fetch(url,options);
}

Logger.log(response.getContentText());


var resource = {'sendAs':[
{'isDefault':true,
'verificationStatus':'accepted',
'sendAsEmail ':alias.alias,
'treatAsAlias':true}]};
Logger.log(资源);
var sendas = Gmail.Users.Settings.SendAs.create(resource,alias.alias);
Logger.log(sendas);



函数reset(){
var service = getOAuthService();
service.reset();
}

ANd我得到一个错误委派拒绝mainaccount@dominio.com



如果我chagen这一行var sendas = Gmail.Users.Settings.SendAs.create(resource,alias.alias);

var sendas = Gmail.Users.Settings.SendAs.create(resource,userEmail);
我得到了一个不同的错误

访问权限限制为已授权域名管理权限的服务帐户

整个域名都是按照此指南全域代表团



有人知道如何创建一个发送与此进程?或者如果代码有问题!

解决方案

下面是一个从您的源代码清理的实例。原始代码存在一些问题:


  • 代码似乎在尝试使用原始的UrlFetchApp.fetch HTTP调用并使用Gmail图书馆。 Gmail资料库并非设计用于使用服务帐户,它只会针对目前不属于您想要的用户,因此我已移除Gmail资料库,而只使用Url Fetch。

  • 您只能调用一次setScope(),否则您会覆盖原来的作用域。如果您要使用多个范围,请在范围之间使用带空格的字符串。

  • 我不确定您想要对AdminDirectory执行什么操作,我已经完全删除了这个范围。如果您想让Admin SDK Directory API调用为用户创建别名电子邮件地址(接收邮件),则需要添加目录范围。 将您的服务帐户值命名为JSON是一个坏主意,因为它覆盖了JSON类的Apps脚本,我已将该变量重命名为service_account。总是一个好主意,以明确您的变量名称以避免这些错误。
  • > var service_account = {
    private_key:----- BEGIN PRIVATE KEY ...,
    client_email:sa-email@example.com ,
    client_id:1234569343,
    user_email:useraccount@example.com
    };
    $ b $ function getOAuthService(user){
    return OAuth2.createService('Service Account')
    .setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/ auth')
    .setTokenUrl('https://accounts.google.com/o/oauth2/token')
    .setPrivateKey(service_account.private_key)
    .setIssuer(service_account.client_email)
    .setSubject(service_account.user_email)
    .setPropertyStore(PropertiesService.getScriptProperties())
    .setScope('https://www.googleapis.com/auth/gmail.settings.sharing https ://www.googleapis.com/auth/gmail.settings.basic')
    }

    函数createAlias(){
    var userEmail ='useraccount@example.com' ;
    var alias ='myalias@example.com';
    var alias_name ='别名用户';

    var service = getOAuthService();
    service.reset();
    if(service.hasAccess()){
    var url ='https://www.googleapis.com/gmail/v1/users/me/settings/sendAs'
    var headers = {
    Authorization:'Bearer'+ service.getAccessToken(),
    Accept:application / json,
    Content-Type:application / json,
    };

    var resource = {
    'sendAsEmail':别名,
    'displayName':alias_name
    };

    var options = {
    'headers':headers,$ b $'method':'POST',
    'payload':JSON.stringify(resource),
    'muteHttpExceptions':true
    };

    Logger.log(options);
    var response = UrlFetchApp.fetch(url,options);
    Logger.log(response.getContentText());



    函数reset(){
    var service = getOAuthService();
    service.reset();
    }

    '''


    hello I would like to add and send as parameter on gmail settings. for all my users, and change this to make a default account to send mail. I know hot to do with the GUI, but I wold like to do with GAS. the code for know is jus ¿t testing for a specific user.

    Reference for Gmail API

    var JSON = {
        "private_key": "-----BEGIN PRIVATE KEY-----\\n-----END PRIVATE KEY-----\n",
        "client_email": "client..@project-id-XXXXX.gserviceaccount.com",
        "client_id": "12345800",
        "user_email": "mainaccount@dominio.com"
    };
    
    function getOAuthService(user) {
        return OAuth2.createService('Service Account')
            .setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
            .setTokenUrl('https://accounts.google.com/o/oauth2/token')
            .setPrivateKey(JSON.private_key)
            .setIssuer(JSON.client_email)
            .setSubject(JSON.user_email)
            .setPropertyStore(PropertiesService.getScriptProperties())
            .setParam('access_type', 'offline')
            .setParam('approval_prompt', 'force')
            .setScope('https://www.googleapis.com/auth/gmail.settings.sharing')
            .setScope('https://www.googleapis.com/auth/gmail.settings.basic');
    }
    
    function createAlias() {
    
    
      var userEmail = 'mainaccount@dominio.com';
      var alias = {
       alias: 'makealiasdefault@dominio.com'
      };
      alias = AdminDirectory.Users.Aliases.insert(alias, userEmail);
     Logger.log('Created alias %s for user %s.', alias.alias, userEmail);
    
      var service = getOAuthService();
    
        service.reset();
        if (service.hasAccess()) {
          var url = 'https://www.googleapis.com/gmail/v1/users/'+userEmail+'/settings/sendAs'
          var headers ={
            "Authorization": 'Bearer ' + service.getAccessToken()
        };
    
          var options = {
            'method':'post',
            'headers': headers,
            'method': 'GET',
            'muteHttpExceptions': true
            };
          var response = UrlFetchApp.fetch(url, options);
          }
    
            Logger.log(response.getContentText());
    
    
          var resource ={'sendAs':[
            {'isDefault':true,
                'verificationStatus':'accepted',
                'sendAsEmail':alias.alias,
                'treatAsAlias':true}]};
          Logger.log(resource);
     var sendas = Gmail.Users.Settings.SendAs.create(resource,alias.alias);
      Logger.log(sendas);
    
    }
    
    function reset() {
        var service = getOAuthService();
        service.reset();
    }
    

    ANd I get an error Delegation denied for mainaccount@dominio.com

    If i chagen this line var sendas = Gmail.Users.Settings.SendAs.create(resource,alias.alias); for this var sendas = Gmail.Users.Settings.SendAs.create(resource,userEmail); I get a different error

    Access restricted to service accounts that have been delegated domain-wide authority

    The domain-wide was made follow this guide Domain-wide Delegation

    Some knows how to create an send as wiht this proccess? or if something is bad with the code!

    解决方案

    Below is a working example cleaned up from your source. A few issues with your original code:

    • The code seems to be trying to both make the raw UrlFetchApp.fetch HTTP call and use the Gmail library. The Gmail library is not designed to work with service accounts, it will only work against the current user which is not what you want, thus I've removed the Gmail library and I'm only using the Url Fetch.
    • You can only call setScope() once otherwise you overwrite the original scopes. If you have more than one scope to use, use a string with spaces between scopes.
    • I'm not really sure what you were trying to do with AdminDirectory, I've removed that entirely. If you want to make Admin SDK Directory API calls to create the alias email address for the user (receive mail) you'll need to add Directory scopes.
    • Naming your service account values to JSON is a bad idea as it overrides the JSON class of Apps Script, I've renamed the variable to service_account. Always a good idea to be specific with your variable names to avoid these kind of errors.

    var service_account = {
        "private_key": "-----BEGIN PRIVATE KEY...",
        "client_email": "sa-email@example.com",
        "client_id": "1234569343",
        "user_email": "useraccount@example.com"
    };
    
    function getOAuthService(user) {
        return OAuth2.createService('Service Account')
            .setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
            .setTokenUrl('https://accounts.google.com/o/oauth2/token')
            .setPrivateKey(service_account.private_key)
            .setIssuer(service_account.client_email)
            .setSubject(service_account.user_email)
            .setPropertyStore(PropertiesService.getScriptProperties())
            .setScope('https://www.googleapis.com/auth/gmail.settings.sharing https://www.googleapis.com/auth/gmail.settings.basic')
    }
    
    function createAlias() {
      var userEmail = 'useraccount@example.com';
      var alias = 'myalias@example.com';
      var alias_name = 'Alias User';
    
      var service = getOAuthService();
      service.reset();
      if (service.hasAccess()) {
        var url = 'https://www.googleapis.com/gmail/v1/users/me/settings/sendAs'
        var headers ={
          "Authorization": 'Bearer ' + service.getAccessToken(),
          "Accept":"application/json", 
          "Content-Type":"application/json",
          };
    
        var resource ={
          'sendAsEmail': alias,
          'displayName': alias_name
          };
    
        var options = {
          'headers': headers,
          'method': 'POST',
          'payload': JSON.stringify(resource),
          'muteHttpExceptions': true
          };
    
        Logger.log(options);
        var response = UrlFetchApp.fetch(url, options);
        Logger.log(response.getContentText());
        }
    }
    
    function reset() {
        var service = getOAuthService();
        service.reset();
    }
    

    '''

    这篇关于创建一个自定义“from”作为GAS和API的别名发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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