Is System.Net.Mail.SmtpClient obsolete in 4.7?

前端 未结 5 1085
心在旅途
心在旅途 2020-12-29 04:10

Few days back I visited a blog that said System.Net.Mail.SmtpClient is obsolete and an open source library MailKit and MimeKit is replacing it.

I can se

5条回答
  •  猫巷女王i
    2020-12-29 04:35

    ... Microsoft has officially marked a .NET class as being replaced by an open source library. The documentation for SmtpClient now reads,

    Obsolete("SmtpClient and its network of types are poorly designed, we strongly recommend you use https://github.com/jstedfast/MailKit and https://github.com/jstedfast/MimeKit instead")

    The main problem with SmtpClient is that it has a confusing connection lifecycle. Connecting to a SMTP server can be time-consuming, especially if authentication is enabled, so each SmtpClient object has an internal connection pool.

    This is a rather strange design. Consider for a moment a typical database connection. When you call Dispose on a SqlClient, the underlying connection is returned to the pool. When you create a new SqlClient, the pool is checked for an active connection with the same connection string.

    With SmtpClient, calling Dispose closes all of the connections and drains that object's connection pool. This means you can't use it with the typical using block pattern.

    A well-known approach of the shared instance like HttpClient cannot be used in SmtpClient.

    Unlike HttpClient, the Send/SendAsync methods are not thread thread-safe. So unless you want to introduce your own synchronization scheme, you can't use it that way either. In fact, the documentation for SmtpClient warns,

    There is no way to determine when an application is finished using the SmtpClient object and it should be cleaned up.

    By contrast, the SMTP client in MailKit represents a simple connection to a single server. By eliminating the complexity caused by internal connection pools, it actually makes it easier to create an application-specific pool for MailKit's connection object.

    Ref: MailKit Officially Replaces .NET's SmtpClient

提交回复
热议问题