通过代理网络阅读Gmail API

时间:2019-01-16 12:49:11

标签: c# proxy gmail-api google-api-dotnet-client

我正在使用gmail API来阅读电子邮件。该代码在专用网络上工作时可以正常工作,但由于代理服务器而在公司网络上运行时会失败。

private static string[] Scopes = { GmailService.Scope.MailGoogleCom };
private static string ApplicationName = "Gmail API .NET Quickstart";

private static void Main(string[] args)
{
    UserCredential credential;

    using (var stream =
        new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
    {
        string credPath = "token.json";
        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(stream).Secrets,
            Scopes,
            "user",
            CancellationToken.None,
            new FileDataStore(credPath, true)).Result;
        Console.WriteLine("Credential file saved to: " + credPath);
    }

    // Create Gmail API service.
    var service = new GmailService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = ApplicationName,
    });

    var inboxlistRequest = service.Users.Messages.List("me");
    inboxlistRequest.LabelIds = "INBOX";
    inboxlistRequest.IncludeSpamTrash = false;
    //get our emails
    var emailListResponse = inboxlistRequest.Execute();

    if (emailListResponse != null && emailListResponse.Messages != null)
    {
        //loop through each email and get what fields you want...
        foreach (var email in emailListResponse.Messages)
        {
            var emailInfoRequest = service.Users.Messages.Get("me", email.Id);
            var emailInfoResponse = emailInfoRequest.Execute();

            if (emailInfoResponse != null)
            {
                String from = "";
                String date = "";
                String subject = "";

                string emailbody = emailInfoResponse.Snippet.Replace(" ", "");
                Console.WriteLine(emailbody);

                //loop through the headers to get from,date,subject, body
                foreach (var mParts in emailInfoResponse.Payload.Headers)
                {
                    if (mParts.Name == "Date")
                    {
                        date = mParts.Value;
                    }
                }
            }
        }
    }
    Console.ReadLine();
}

我尝试在app.config中关注xml,但是没有运气。

  <system.net>
    <defaultProxy>
      <proxy
        proxyaddress="my proxy and port"
      />
    </defaultProxy>
  </system.net> 

我已经查看了gmailService中的httpclientfactory属性,但不知道如何使用它。请问我可以在上述代码中进行哪些更改,以便可以通过代理运行此更改。

0 个答案:

没有答案