简体   繁体   中英

System.Net.Mail The requested service provider could not be loaded or initialized

I got the following exception when trying to send email using System.Net.Mail.SmtpClient:

System.Net.Mail.SmtpException: The SMTP host was not found.

Inner exception:

System.Net.Sockets.SocketException: The requested service provider could not be loaded or initialized

My email sending code is rather simple:

private async Task SendEmail(string to, string subject, string email)
{
    MailMessage msg = null;
    SmtpClient smtp = null;
    try
    {
        var set = Settings.Default;
        msg = new MailMessage(set.EmailFrom, to, subject, email);
        smtp = new SmtpClient(set.SMTPServer, set.Port)
        {
            EnableSsl = true,
            Credentials = new NetworkCredential(set.EmailUsername, set.EmailPassword),
            Timeout = 20000
        };
        await smtp.SendMailAsync(msg);
    }
    catch (Exception e)
    {
        _log.Error("Error on sending email", e);
        throw;
    }
    finally
    {
        if (msg != null) msg.Dispose();
        if (smtp != null) smtp.Dispose();
    }
}

This error does not happen each time, but rather often. I tried to google it but have not found anything useful. The internet connection seems to be stable when I get this error.

Any ideas why this could happen?

Apologies for not posting this as a comment, I don't have sufficient rep.

I run a process using a very similar implementation to that and I have had the same thing happen to me. Try reducing SMTP the timeout, a new connection will be refused if there are too many requests that haven't let go of their existing connection yet. It's helped with my specific implementation.

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