Question

We are changing our email to Office 365, which force me to EnableSSL when I send Email from .NET. Since our Intranet Web Application run under .net 3.5, it look like I cannot enable SSL for SmtpClient in Web.config. So I do something like this :

Dim Smtp As New System.Net.Mail.SmtpClient
Smtp.EnableSsl = Boolean.Parse(System.Configuration.ConfigurationManager.AppSettings("SmtpEnableSsl"))
Smtp.Send(eMail)

But this ASP.net website is also configured to Send E-mail for Health Monitoring Notifications. I use the SimpleMailWebEventProvider to do so, but it look like there is no option to EnableSsl on this provider.

What should I do to fix that?

Was it helpful?

Solution

I found this article that show how to force EnableSsl into a MailWebEventProvider.

I modified it so it use the SimpleMailWebEventProvider instead of the TemplatedMailWebEventProvider and use my AppSettings from the web.config to toggle the EnableSsl setting without changing the code, so the administrator will be able to switch it at will.

using System;
using System.Collections.Specialized;
using System.Reflection;
using System.Web.Management; 
using System.Net.Mail;
using System.Configuration;

/// <summary>
/// Summary description for SimpleMailWithSslWebEventProvider
/// </summary>
public class SimpleMailWithSslWebEventProvider : WebEventProvider 
{
    private SimpleMailWebEventProvider _SimpleProvider;
    public SimpleMailWithSslWebEventProvider() 
    {
        ConstructorInfo constructor = typeof(SimpleMailWebEventProvider) 
            .GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, 
                            null, new Type[0], null);
        _SimpleProvider = (SimpleMailWebEventProvider)constructor 
            .Invoke(null); 
    } 
    public override void Initialize(string name, NameValueCollection config) 
    { 
        if (config == null) 
        { 
            throw new ArgumentNullException("config"); 
        }
        _SimpleProvider.Initialize(name, config); 

        FieldInfo field = typeof(MailWebEventProvider) 
            .GetField("_smtpClient", 
                      BindingFlags.Instance | BindingFlags.NonPublic);
        field.SetValue(_SimpleProvider, new SmtpClientWithSsl()); 
    } 


    public override void Flush() 
    {
        _SimpleProvider.Flush(); 
    } 
    public override void ProcessEvent(WebBaseEvent raisedEvent) 
    {
        _SimpleProvider.ProcessEvent(raisedEvent); 
    } 
    public override void Shutdown() 
    {
        _SimpleProvider.Shutdown(); 
    } 
}
public class SmtpClientWithSsl : SmtpClient {
    public SmtpClientWithSsl() {
        base.EnableSsl = Boolean.Parse(ConfigurationManager.AppSettings.Get("SmtpEnableSsl"));
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top