Setting multiple SMTP settings in web.config?

前端 未结 8 1365
庸人自扰
庸人自扰 2020-12-01 00:42

I am building an app that needs to dynamically/programatically know of and use different SMTP settings when sending email.

I\'m used to using the system.net/mailSet

8条回答
  •  误落风尘
    2020-12-01 01:32

    This is how i use it and it works fine for me (settings are similar to Mikko answer):

    1. First set up config sections:

      
        
          
            

    2. Then it would be the best to create a some sort of wrapper. Note that most of code below was taken from .NET source code for SmtpClient here

      public class CustomSmtpClient
      {
          private readonly SmtpClient _smtpClient;
      
          public CustomSmtpClient(string sectionName = "default")
          {
              SmtpSection section = (SmtpSection)ConfigurationManager.GetSection("mailSettings/" + sectionName);
      
              _smtpClient = new SmtpClient();
      
              if (section != null)
              {
                  if (section.Network != null)
                  {
                      _smtpClient.Host = section.Network.Host;
                      _smtpClient.Port = section.Network.Port;
                      _smtpClient.UseDefaultCredentials = section.Network.DefaultCredentials;
      
                      _smtpClient.Credentials = new NetworkCredential(section.Network.UserName, section.Network.Password, section.Network.ClientDomain);
                      _smtpClient.EnableSsl = section.Network.EnableSsl;
      
                      if (section.Network.TargetName != null)
                          _smtpClient.TargetName = section.Network.TargetName;
                  }
      
                  _smtpClient.DeliveryMethod = section.DeliveryMethod;
                  if (section.SpecifiedPickupDirectory != null && section.SpecifiedPickupDirectory.PickupDirectoryLocation != null)
                      _smtpClient.PickupDirectoryLocation = section.SpecifiedPickupDirectory.PickupDirectoryLocation;
              }
          }
      
          public void Send(MailMessage message)
          {
              _smtpClient.Send(message);
          }
      

      }

    3. Then simply send email:

      new CustomSmtpClient("mailings").Send(new MailMessage())

提交回复
热议问题