c# - 有什么办法可以关闭邮件 smtp session 吗?

标签 c# .net smtp

我正在使用 Gmail STMP 服务器发送电子邮件。它工作得很好。但是几天以来,它有时会停止工作。现在,它只有 10 次中的 5 次有效。

Exception: Failure Sending Email

Inner Exception: Unable to connect to remote server.

在与托管技术支持交谈后,他们说他们的服务器上存在邮件 session 限制。这是一个“共享主机”,所以当它超过时,所有新连接都会被阻塞。他们说他们正在努力修复它。但也说请检查您是否“正确关闭邮件 session ”。

我查看了它,但没有 Close()Dispose()。我还读到没有对 SMTP 传输的确认?

请让我知道是否有关闭邮件 session 的方法?或解决此问题的任何解决方法。

我正在使用 System.Net.Mail:

MailMessage msg = new MailMessage();
SmtpClient sc = new SmtpClient("smtp.gmail.com", 587);
NetworkCredential info = new NetworkCredential("email", "password");

还有另一种调用sc.Send()的方法。

最佳答案

System.Net.Mail.SmtpClient实现了 IDisposable,因此我建议您使用它。使用 using阻止以确保它得到正确处理。

请特别注意 System.Web.Mail 的使用已被弃用,取而代之的是 System.Net.Mail

using (SmtpClient client = new SmtpClient("mail.google.com")) 
{

}

您正在使用 System.Net.Mail。在那种情况下,您会发现 SMTPClient 确实有一个 Dispose方法(因为它实现了 IDisposable),它将优雅地关闭 SMTP 连接。但是,使用 using block 而不是直接调用 Dispose 被认为是更好的做法。最后,请注意链接文档中的以下内容:

The SmtpClient class has no Finalize method. So an application must call Dispose to explicitly free up resources.

The Dispose method iterates through all established connections to the SMTP server specified in the Host property and sends a QUIT message followed by gracefully ending the TCP connection. The Dispose method also releases the unmanaged resources used by the underlying Socket.

关于c# - 有什么办法可以关闭邮件 smtp session 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5936997/

相关文章:

c# - AreaRegistration.RegisterAllAreas() 在使用 Application Insights 时永远不会完成

c# - AutoMapper 映射自定义值 ForMember

.net - 柯里化(Currying)委托(delegate)参数的最佳模式是什么(使用 .NET 2.0 或更高版本)?

php - 无法在 codeigniter 3 中使用 SMTP gmail 配置发送电子邮件

python - 发送自定义 Mime 类型 Google App Engine 电子邮件

c# - 如何从电子邮件中获取收件人

c# - 在 csproj 文件中引用 AssemblyFileVersion

.net - 使用 Entity Framework 批准对实时数据的更改

C# SMTP 邮件不工作?

c# - 以无边界形式绘制夹具