简体   繁体   中英

SmtpClient.Send will send a message AND timeout

I am updating some older code to be integrated with SQL. I work for a company that occasionally sends out bulk emails that slows down the mail server immensely. We want to queue the emails into the database if they start building up. While testing some changes to the code, I noticed that I would receive the email and the client would still timeout. This would cause problems as the client would then set the email in the queue and I would receive it later when another service attempts to clean out the database.

SmtpClient emailClient = new SmtpClient(Settings.SmtpServer);
emailClient.Timeout = 100;

bool sent = false;
try
{
    using (Impersonate imp = DA.GetImpersonator())
    {
        emailClient.Send(message);
        sent = true;
    }
}
catch (SmtpException) { }
finally
{
    if (sent)
    {
        email.IsSent = true;
        DA.Save(email);
    }
}

Out of 10 test runs, 9 timed out, 1 succeeded; I received 7 emails.

From looking at the spec, the timeout only promises that the method will return within that time, not that the sending has been stopped.

If you need to send multiple emails, consider using the SendAsync method and subscribe to the SendCompleted event to determine the success / failure of sending the email.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM