The best way to send mail using SmtpClient?

I am looking for good performance when sending a large number of emails.

I heard that the correct way to do this is to open the connection, send ~ 20 letters and close the connection. And do it again and again. Is it correct?

And how does SmtpClient work, does it open a connection for its own life? (not IDisposable, it doesn’t look like that) Or does it open a connection for every email you send? Or does he have a connection open all the time? Or does he have some kind of magic that opens and closes connections when it comes up?

I would like to know, so I know how I should initiate SmtpClient. As a singleton or only for a piece of messages ...

+5
source share
1 answer

It sends only one MailMessage message from the connection. In fact, it does not even close the connection. He sends mail, but then he does not inform the mail server that he wants to exit. That way, it just leaves it open until the main thread pool decides to close the socket.

Here is the internal code from Reflector:

...
        this.GetConnection();
        fileMailWriter = this.transport.SendMail((message.Sender != null) ? message.Sender : message.From, recipients, message.BuildDeliveryStatusNotificationString(), out exception);
        }
        catch (Exception exception2)
        {
            if (Logging.On)
            {
                Logging.Exception(Logging.Web, this, "Send", exception2);
            }
            if ((exception2 is SmtpFailedRecipientException) && !((SmtpFailedRecipientException) exception2).fatal)
            {
                throw;
            }
            this.Abort();
            if (this.timedOut)
            {
                throw new SmtpException(SR.GetString("net_timeout"));
            }
            if (((exception2 is SecurityException) || (exception2 is AuthenticationException)) || (exception2 is SmtpException))
            {
                throw;
            }
            throw new SmtpException(SR.GetString("SmtpSendMailFailure"), exception2);
        }

btw, here is more information about SmtpClient not issuing a QUIT command. https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=146711&wa=wsignin1.0

Edit: view the dead link above at web.archive.org

, SmtpClient.ServicePoint.MaxTimeout 1. , QUIT.

+7

All Articles