Is there a way to do a batch request to get SendAs emails from multiple or all users?
Currently we are using a service account with user impersonation to go through each user and get the SendAs email list - lot of requests.
- GmailService as service - this is impersonated as the user.
- service.Users.Settings.SendAs.List("me").Execute();
P.S. I posted this in google group, but just read a post that said the forum is now read-only! It's weird that it allowed me to make a new post (and obviously i was thinking that the post has to be approved)
Thanks!
static string[] Scopes = { GmailService.Scope.MailGoogleCom,
GmailService.Scope.GmailSettingsBasic,
GmailService.Scope.GmailSettingsSharing,
GmailService.Scope.GmailModify};
/// <summary>
/// Gets default send as email address from user's gmail - throws error if valid domain is not used as default sendAs
/// </summary>
/// <param name="primaryEmailAddress">User's email address to use to impersonate</param>
/// <param name="excludedDomains">Domains to exclude in the results - example: @xyz.org</param>
/// <returns>default SendAs email address</returns>
public static string GetDefaultSendAs(string primaryEmailAddress, string[] excludedDomains)
{
string retVal = string.Empty;
GmailService service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer =
Auth.GetServiceAccountAuthorization
(scopes: Scopes, clientSecretFilePath: Constant.ClientSecretFilePath, impersonateAs: primaryEmailAddress)
});
var result = service.Users.Settings.SendAs.List("me").Execute();
SendAs s = result.SendAs.First(e => e.IsDefault == true);
bool incorrectSendAs = false;
if (s != null)
{
foreach (string domain in excludedDomains)
{
// Check if email ends with domain
if (s.SendAsEmail.ToLower().EndsWith("@" + domain.TrimStart('@'))) // removes @ and adds back - makes sure to domain start with @.
{
incorrectSendAs = true;
}
}
}
if (s != null && !incorrectSendAs)
retVal = s.SendAsEmail;
else
throw new Exception($"{primaryEmailAddress}, valid default SendAs email not set.");
System.Threading.Thread.Sleep(10);
return retVal;
}
Auth Code:
class Auth
{
internal static ServiceAccountCredential GetServiceAccountAuthorization(string[]scopes, string clientSecretFilePath, string impersonateAs = "admin@xyz.org")
{
ServiceAccountCredential retval;
if (impersonateAs == null || impersonateAs == string.Empty)
{
throw new Exception("Please provide user to impersonate");
}
else
{
using (var stream = new FileStream(clientSecretFilePath, FileMode.Open, FileAccess.Read))
{
retval = GoogleCredential.FromStream(stream)
.CreateScoped(scopes)
.CreateWithUser(impersonateAs)
.UnderlyingCredential as ServiceAccountCredential;
}
}
return retval;
}
API client access: