创建自定义“from"使用 GAS 和 API 发送别名 [英] Creates a custom "from" send-as alias with GAS and APIs

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

问题描述

你好,我想在 gmail 设置中添加并发送为参数.对于我的所有用户,并更改此设置以创建发送邮件的默认帐户.我知道用 GUI 很热,但我喜欢用 GAS.知道的代码只是对特定用户进行测试.

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.

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();
}

我收到一个错误,为 mainaccount@dominio.com 拒绝委托

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

如果我修改这一行 var sendas = Gmail.Users.Settings.SendAs.create(resource,alias.alias);为了这var sendas = Gmail.Users.Settings.SendAs.create(resource,userEmail);我得到一个不同的错误

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

域范围遵循本指南域范围委派

有些人知道如何使用此过程创建发送?或者代码有问题!

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:

  • 该代码似乎试图同时进行原始 UrlFetchApp.fetch HTTP 调用并使用 Gmail 库.Gmail 库不是为使用服务帐户而设计的,它仅适用于当前用户,这不是您想要的,因此我删除了 Gmail 库并且我只使用 Url Fetch.
  • 您只能调用 setScope() 一次,否则您将覆盖原始范围.如果您有多个范围要使用,请使用范围之间有空格的字符串.
  • 我不太确定你想用 AdminDirectory 做什么,我已经完全删除了.如果您想通过 Admin SDK Directory API 调用为用户创建别名电子邮件地址(接收邮件),您需要添加目录范围.
  • 将您的服务帐户值命名为 JSON 是一个坏主意,因为它会覆盖 Apps 脚本的 JSON 类,我已将该变量重命名为 service_account.使用特定的变量名称以避免此类错误始终是一个好主意.
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天全站免登陆