如何创建 Google BaseClientService.Initializer 的实例
本文关键字:BaseClientService Initializer 实例 Google 何创建 创建 | 更新日期: 2023-09-27 17:56:09
我想知道如何创建Google BaseClientService.Initializer
的实例。 我需要使用该BaseClientService.Initializer
创建GmailService
实例,然后使用此GmailService
实例创建UsersResource
实例。
Google.Apis.Services.BaseClientService.Initializer initializer = new BaseClientService.Initializer();
initializer.ApiKey = "MyApiKey";
initializer.ApplicationName = "MyProject";
initializer.DefaultExponentialBackOffPolicy = Google.Apis.Http.ExponentialBackOffPolicy.None;
Google.Apis.Gmail.v1.GmailService gmailService = new GmailService(initializer);
Google.Apis.Gmail.v1.UsersResource usersResource = new UsersResource(gmailService);
UsersResource.MessagesResource messagesResource = usersResource.Messages;
首先转到下面的链接,然后在您的Google帐户中打开一个应用程序。运行代码后,您将第一次收到异常,为您提供一个地址,并在您的Google帐户中启用API。
https://console.developers.google.com/apis/dashboard?project=super-pharm-log-notifications
static string[] Scopes = { GmailService.Scope.GmailCompose, GmailService.Scope.GmailSend, GmailService.Scope.GmailInsert };
static private BaseClientService.Initializer initializeGmailAccountServices()
{
string appRoot = null;
if (System.Web.HttpContext.Current == null)
{
appRoot = Environment.CurrentDirectory;
}
else
{
appRoot = System.Web.HttpContext.Current.Server.MapPath(@"~'");
}
string path = Path.Combine(appRoot, DBConstants.GMAIL_CREDENTIALS_PATH);
UserCredential credential;
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
ClientSecrets secrets = GoogleClientSecrets.Load(stream).Secrets;
var t = GoogleWebAuthorizationBroker.AuthorizeAsync(secrets, Scopes, "user", CancellationToken.None);
t.Wait();
credential = t.Result;
}
return= new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "your application name",
};
}
private static string Base64UrlEncode(string input)
{
var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
// Special "url-safe" base64 encode.
return Convert.ToBase64String(inputBytes)
.Replace('+', '-')
.Replace('/', '_')
.Replace("=", "");
}