我發現this article顯示如何強制EnableSsl
進入MailWebEventProvider
。
我修改了它,所以它使用SimpleMailWebEventProvider
,而不是TemplatedMailWebEventProvider
,用我AppSettings
從web.config
來切換EnableSsl
設置而無需修改代碼,這樣管理員就可以隨意切換它。
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"));
}
}