首页 > 解决方案 > 在 C# 中调用 Gmail 服务 API 时出现 System.Net.Http.HttpRequestException

问题描述

在 C# 中使用 Gmail API 时会随机发生以下异常。我的代码可以正常工作几个小时,没有任何问题。以下异常以随机方式发生。要解决此问题,我只需要重新启动我的应用程序或重新启动 PC。重新启动后,一切正常。我想知道如何永久修复此异常。

03-Jun-2021 17:18:13,755 [INFO ] MailApi+<GmailSendUsingREST>d__27 MoveNext             - Email notification send error System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
   at System.Net.TlsStream.EndWrite(IAsyncResult asyncResult)
   at System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar)
   --- End of inner exception stack trace ---
   at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context)
   at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar)
   --- End of inner exception stack trace ---
   at Google.Apis.Http.ConfigurableMessageHandler.<SendAsync>d__69.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Google.Apis.Requests.ClientServiceRequest`1.<ExecuteUnparsedAsync>d__34.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Google.Apis.Requests.ClientServiceRequest`1.Execute()

代码:

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

 var result = service.Users.Messages.Send(msg, "me").Execute();

Messages.Send 发生异常。

更新:

有关可能的情况,请参阅Stackoverflow 上的此线程。

标签: c#oauth-2.0google-oauthgmail-apigoogle-api-dotnet-client

解决方案


好吧,您需要注意的事项很少。

  1. 我认为 Gmail 对您每天可以发送的电子邮件有限制。限制数量取决于您拥有的帐户类型。

  2. 确保打开 SSL 或 TLS 以实现安全连接。

  3. 底层连接已关闭:可能是当您可以访问互联网但您没有访问 Web 服务的数据包时。

  4. System.Security.Authentication.AuthenticationException:确保您的身份验证凭据正确。最后,

  5. 如果您使用 gmail SMTP 发送电子邮件,请确保在您使用的帐户中打开安全性较低的应用程序访问。

我希望这有帮助。快乐编码!


推荐阅读