【发布时间】:2019-03-01 12:14:42
【问题描述】:
有没有办法进行批量请求以获取来自多个或所有用户的 SendAs 电子邮件?
目前我们正在使用模拟用户的服务帐户来遍历每个用户并获取 SendAs 电子邮件列表 - 大量请求。
- GmailService 即服务 - 这被冒充为用户。
- service.Users.Settings.SendAs.List("me").Execute();
附:我在 google 群组中发布了这个,但刚刚阅读了一篇帖子,上面说论坛现在是只读的!奇怪的是它允许我发一个新帖子(显然我认为这个帖子必须被批准)
谢谢!
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;
}
授权码:
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;
}
【问题讨论】:
-
请编辑您的问题并附上您的授权码。我想看看您是如何使用服务帐户登录的。如果您不介意,我希望看到 gsuite 的一些屏幕截图,您可以在其中设置服务帐户的域委派,随时将不应该共享的内容留空。
-
更新了!谢谢!
-
管理员可以看到其他用户的 SendAs 电子邮件地址吗?也许我们只需要使用一些企业级管理员用户来模拟。
-
x 我的最后一条评论 - 如果我们尝试使用企业管理员获取其他用户的 SendAs,则会收到委托错误。错误:消息[Delegation denied for admin@xyz.org] Location[-] Reason[forbidden] Domain[global]
-
感谢您发布您的代码,多年来我一直在寻找用户模拟的示例。问题出现了,我没有一个可以链接的工作示例,因为我不再可以访问 gusite 帐户。您的代码将来可能会对其他人有所帮助。
标签: c# google-api-dotnet-client service-accounts google-workspace