How to enable SSL for SmtpClient in Web.config

前端 未结 10 1135
再見小時候
再見小時候 2020-12-05 07:03

Is there a way to set the EnableSSL from the web.config?

I could set this property in code, but that wouldn\'t work for the Simple Mail Web Event and other classes t

相关标签:
10条回答
  • 2020-12-05 07:54

    This is the code I use in my web.config file.

    0 讨论(0)
  • 2020-12-05 07:55

    I think there's a bug in the MailSettingsSectionGroup. See below code:

    Configuration configurationFile = WebConfigurationManager.OpenWebConfiguration("~/web.config");
    var mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
    
    _smtpClient.Host = mailSettings.Smtp.Network.Host;
    _smtpClient.Port = mailSettings.Smtp.Network.Port;
    _smtpClient.EnableSsl = mailSettings.Smtp.Network.**EnableSsl**;
    _smtpClient.Credentials = new System.Net.NetworkCredential(mailSettings.Smtp.Network.UserName, mailSettings.Smtp.Network.Password);
    _smtpClient.UseDefaultCredentials = false;
    

    It seems that EnableSsl does not exist as a property under Network because when I run and debug this, I can see the value, but can't compile the code due to missing ExtensionMethod.

    0 讨论(0)
  • 2020-12-05 07:56

    For .NET 3 and earlier: You can't. You have to manage it by hand.

    For more information you can see https://blogs.msdn.microsoft.com/vikas/2008/04/29/bug-asp-net-2-0-passwordrecovery-web-control-cannot-send-emails-to-ssl-enabled-smtp-servers/.

    For .NET 4: You can.

    See http://theoldsewingfactory.com/2011/01/06/enable-ssl-in-web-config-for-smtpclient/

    <configuration>
        <system.net>
            <mailSettings>
                <smtp deliveryMethod=”network”>
                    <network host="localhost"
                             port="25"
                             enableSsl="true"
                             defaultCredentials="true" />
                </smtp>
            </mailSettings>
        </system.net>
    </configuration>
    
    0 讨论(0)
  • 2020-12-05 08:00

    I have a dirty workaround (until .NET 4.0 comes out). Instead of changin my code it relies on the used port to determine if SSL is required or not.

    var client = new SmtpClient();
    client.EnableSsl = client.Port == 587 || client.Port == 465;
    // This could also work
    //client.EnableSsl = client.Port != 25;
    

    I said it was a dirty hack, but it working fine for the different configurations that we encounter.

    0 讨论(0)
提交回复
热议问题