Creates a custom “from” send-as alias with GAS and

2019-02-25 21:40发布

问题:

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!

回答1:

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

'''