How to enable SSL for SmtpClient in Web.config

前端 未结 10 1155
再見小時候
再見小時候 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:48

    I appears the class is sealed, so i made a manual extension. I thought i'd provide it for others here. Hope it can be of use to others.

    /// 
    /// OldSchool extension of SmtpNetWorkElement, since it's sealed.
    /// 
    public class SmtpNetworkElementEx
    {
        private readonly SmtpNetworkElement m_SmtpNetWorkElement;
    
        /// 
        /// Initializes a new instance of the  class.
        /// 
        public SmtpNetworkElementEx()
        {
            Configuration configurationFile = WebConfigurationManager.OpenWebConfiguration("~/web.config");
            var mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
    
            if (mailSettings == null)
                return;
    
            m_SmtpNetWorkElement = mailSettings.Smtp.Network;
        }
    
        public string Host { get { return m_SmtpNetWorkElement.Host; } }
        public bool DefaultCredentials { get { return m_SmtpNetWorkElement.DefaultCredentials; } }
        public string ClientDomain { get { return m_SmtpNetWorkElement.ClientDomain; } }
        public string TargetName { get { return m_SmtpNetWorkElement.TargetName; } }
        public int Port { get { return m_SmtpNetWorkElement.Port; } }
        public string UserName { get { return m_SmtpNetWorkElement.UserName; } }
        public string Password { get { return m_SmtpNetWorkElement.Password; } }
        public bool EnableSsl { get { return Convert.ToBoolean(m_SmtpNetWorkElement.ElementInformation.Properties["enableSsl"].Value); } }
    }
    

    Use this way:

    var smtpSettings = new SmtpNetworkElementEx();
    
    _smtpClient.Host = smtpSettings.Host;
    _smtpClient.Port = smtpSettings.Port;
    _smtpClient.EnableSsl = smtpSettings.EnableSsl;
    _smtpClient.Credentials = new System.Net.NetworkCredential(smtpSettings.UserName, smtpSettings.Password);
    

提交回复
热议问题