如何创建Google BaseClientService.Initializer的实例

时间:2016-07-08 07:37:24

标签: c# gmail

我想知道如何创建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;

1 个答案:

答案 0 :(得分:1)

首先转到下面的链接并在您的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("=", "");
            }