【问题标题】:Setting multiple SMTP settings in web.config?在 web.config 中设置多个 SMTP 设置?
【发布时间】:2011-05-20 18:25:02
【问题描述】:

我正在构建一个应用程序,该应用程序需要在发送电子邮件时以动态/编程方式了解并使用不同的 SMTP 设置。

我习惯于使用 system.net/mailSettings 方法,但据我了解,它一次只允许一个 SMTP 连接定义,由 SmtpClient() 使用。

但是,我需要更多类似 connectionStrings 的方法,我可以在其中根据键/名称提取一组设置。

有什么建议吗?我愿意跳过传统的 SmtpClient/mailSettings 方法,我认为必须...

【问题讨论】:

    标签: c# web-config smtp mailsettings


    【解决方案1】:

    我需要在 web.config 中有不同的 smtp 配置,具体取决于环境:开发、登台和生产。

    这是我最终使用的:

    在 web.config 中:

    <configuration>
      <configSections>
        <sectionGroup name="mailSettings">
          <section name="smtp_1" type="System.Net.Configuration.SmtpSection"/>
          <section name="smtp_2" type="System.Net.Configuration.SmtpSection"/>
          <section name="smtp_3" type="System.Net.Configuration.SmtpSection"/>
        </sectionGroup>
      </configSections>
      <mailSettings>
        <smtp_1 deliveryMethod="Network" from="mail1@temp.uri">
          <network host="..." defaultCredentials="false"/>
        </smtp_1>
        <smtp_2 deliveryMethod="Network" from="mail2@temp.uri">
          <network host="1..." defaultCredentials="false"/>
        </smtp_2>
        <smtp_3 deliveryMethod="Network" from="mail3@temp.uri">
          <network host="..." defaultCredentials="false"/>
        </smtp_3>
      </mailSettings>
    </configuration>
    

    然后在代码中:

    return (SmtpSection)ConfigurationManager.GetSection("mailSettings/smtp_1");
    return (SmtpSection)ConfigurationManager.GetSection("mailSettings/smtp_2");
    return (SmtpSection)ConfigurationManager.GetSection("mailSettings/smtp_3");
    

    【讨论】:

    • Miko 和@alphadog 您的回答似乎适用于我遇到的类似情况,但我不知道如何使用 Mikko 在他的回答“return (SmtpSection)... 。”你能详细说明一下吗?虽然可能不合适,但我将使用我拥有的代码创建一个“答案”,而不是在 SO 上提出新问题。
    • @Mikko 您的代码没有得到很好的解释。如何使用返回的 SmtpSection?
    【解决方案2】:
    SmtpSection smtpSection =  (SmtpSection)ConfigurationManager.GetSection("mailSettings/smtp_1");
    
    SmtpClient smtpClient = new SmtpClient(smtpSection.Network.Host, smtpSection.Network.Port);
    smtpClient.Credentials = new NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password);
    

    【讨论】:

    • 只是一个额外的帮助:您需要声明 System.Net.Configuration 命名空间才能使用 SmtpSection。还有用于 NetworkCredential 的 System.Net。
    • “发件人”字段呢?
    【解决方案3】:

    这就是我使用它的方式,它对我来说很好用(设置类似于 Mikko 的答案):

    1. 首先设置配置部分:

      <configuration>
        <configSections>
          <sectionGroup name="mailSettings">
            <section name="default" type="System.Net.Configuration.SmtpSection" />
            <section name="mailings" type="System.Net.Configuration.SmtpSection" />
            <section name="partners" type="System.Net.Configuration.SmtpSection" />
          </sectionGroup>
        </configSections>
      <mailSettings>
        <default deliveryMethod="Network">
          <network host="smtp1.test.org" port="587" enableSsl="true"
                 userName="test" password="test"/>
        </default>
        <mailings deliveryMethod="Network">
          <network host="smtp2.test.org" port="587" enableSsl="true"
                 userName="test" password="test"/>
        </mailings>
      <partners deliveryMethod="Network">
        <network host="smtp3.test.org" port="587" enableSsl="true"
                 userName="test" password="test"/>
      </partners>
      

    2. 那么最好创建某种包装器。请注意,以下大部分代码取自 SmtpClient here 的 .NET 源代码

      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. 然后只需发送电子邮件:

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

    【讨论】:

      【解决方案4】:

      这可能对某人有帮助,也可能对某人没有帮助,但如果你在这里寻找用于多个 smtp 配置的 Mandrill 设置,我最终创建了一个继承自 SmtpClient 类的类,下面这个人的代码非常好:https://github.com/iurisilvio/mandrill-smtp.NET

          /// <summary>
      /// Overrides the default SMTP Client class to go ahead and default the host and port to Mandrills goodies.
      /// </summary>
      public class MandrillSmtpClient : SmtpClient
      {
      
          public MandrillSmtpClient( string smtpUsername, string apiKey, string host = "smtp.mandrillapp.com", int port = 587 )
              : base( host, port )
          {
      
              this.Credentials = new NetworkCredential( smtpUsername, apiKey );
      
              this.EnableSsl = true;
          }
      }
      

      这是一个如何调用它的示例:

              [Test]
          public void SendMandrillTaggedEmail()
          {
      
              string SMTPUsername = _config( "MandrillSMTP_Username" );
              string APIKey = _config( "MandrillSMTP_Password" );
      
              using( var client = new MandrillSmtpClient( SMTPUsername, APIKey ) ) {
      
                  MandrillMailMessage message = new MandrillMailMessage() 
                  { 
                      From = new MailAddress( _config( "FromEMail" ) ) 
                  };
      
                  string to = _config( "ValidToEmail" );
      
                  message.To.Add( to );
      
                  message.MandrillHeader.PreserveRecipients = false;
      
                  message.MandrillHeader.Tracks.Add( ETrack.opens );
                  message.MandrillHeader.Tracks.Add( ETrack.clicks_all );
      
                  message.MandrillHeader.Tags.Add( "NewsLetterSignup" );
                  message.MandrillHeader.Tags.Add( "InTrial" );
                  message.MandrillHeader.Tags.Add( "FreeContest" );
      
      
                  message.Subject = "Test message 3";
      
                  message.Body = "love, love, love";
      
                  client.Send( message );
              }
          }
      

      【讨论】:

        【解决方案5】:

        当您准备好发送邮件时,只需传递相关详细信息,并将所有这些设置存储在您的 web.config 的应用程序设置中。

        例如,在web.config中创建不同的AppSettings(如“EmailUsername1”等),就可以完全分别调用如下:

                System.Net.Mail.MailMessage mail = null;
                System.Net.Mail.SmtpClient smtp = null;
        
                mail = new System.Net.Mail.MailMessage();
        
                //set the addresses
                mail.From = new System.Net.Mail.MailAddress(System.Configuration.ConfigurationManager.AppSettings["Email1"]);
                mail.To.Add("someone@example.com");
        
                mail.Subject = "The secret to the universe";
                mail.Body = "42";
        
                //send the message
                smtp = new System.Net.Mail.SmtpClient(System.Configuration.ConfigurationManager.AppSettings["YourSMTPServer"]);
        
                //to authenticate, set the username and password properites on the SmtpClient
                smtp.Credentials = new System.Net.NetworkCredential(System.Configuration.ConfigurationManager.AppSettings["EmailUsername1"], System.Configuration.ConfigurationManager.AppSettings["EmailPassword1"]);
                smtp.UseDefaultCredentials = false;
                smtp.Port = System.Configuration.ConfigurationManager.AppSettings["EmailSMTPPort"];
                smtp.EnableSsl = false;
        
                smtp.Send(mail);
        

        【讨论】:

          【解决方案6】:

          我有同样的需求,标记的答案对我有用。

          我做了这些改动

          web.config:

                <configSections>
                  <sectionGroup name="mailSettings2">
                    <section name="noreply" type="System.Net.Configuration.SmtpSection"/>
                  </sectionGroup>
                  <section name="othersection" type="SomeType" />
                </configSections>
          
                <mailSettings2>
                  <noreply deliveryMethod="Network" from="noreply@host.com"> // noreply, in my case - use your mail in the condition bellow
                    <network enableSsl="false" password="<YourPass>" host="<YourHost>" port="25" userName="<YourUser>" defaultCredentials="false" />
                  </noreply>
                </mailSettings2>
                ... </configSections>
          

          然后,我有一个发送邮件的线程:

          SomePage.cs

          private bool SendMail(String From, String To, String Subject, String Html)
              {
                  try
                  {
                      System.Net.Mail.SmtpClient SMTPSender = null;
          
                      if (From.Split('@')[0] == "noreply")
                      {
                          System.Net.Configuration.SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("mailSettings2/noreply");
                          SMTPSender = new System.Net.Mail.SmtpClient(smtpSection.Network.Host, smtpSection.Network.Port);
                          SMTPSender.Credentials = new System.Net.NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password);
                          System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
                          Message.From = new System.Net.Mail.MailAddress(From);
          
                          Message.To.Add(To);
                          Message.Subject = Subject;
                          Message.Bcc.Add(Recipient);
                          Message.IsBodyHtml = true;
                          Message.Body = Html;
                          Message.BodyEncoding = Encoding.GetEncoding("ISO-8859-1");
                          Message.SubjectEncoding = Encoding.GetEncoding("ISO-8859-1");
                          SMTPSender.Send(Message);
          
                      }
                      else
                      {
                          SMTPSender = new System.Net.Mail.SmtpClient();
                          System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
                          Message.From = new System.Net.Mail.MailAddress(From);
          
                          SMTPSender.EnableSsl = SMTPSender.Port == <Port1> || SMTPSender.Port == <Port2>;
          
                          Message.To.Add(To);
                          Message.Subject = Subject;
                          Message.Bcc.Add(Recipient);
                          Message.IsBodyHtml = true;
                          Message.Body = Html;
                          Message.BodyEncoding = Encoding.GetEncoding("ISO-8859-1");
                          Message.SubjectEncoding = Encoding.GetEncoding("ISO-8859-1");
                          SMTPSender.Send(Message);
                      }
                  }
                  catch (Exception Ex)
                  {
                      Logger.Error(Ex.Message, Ex.GetBaseException());
                      return false;
                  }
                  return true;
              }
          

          谢谢你=)

          【讨论】:

            【解决方案7】:

            我最终构建了自己的自定义配置加载器,用于 EmailService 类。配置数据可以像连接字符串一样存储在 web.config 中,并通过名称动态拉取。

            【讨论】:

              【解决方案8】:

              看来您可以使用不同的 SMTP 字符串进行初始化。

              SmtpClient 客户端 = new SmtpClient(server);

              http://msdn.microsoft.com/en-us/library/k0y6s613.aspx

              我希望这就是你要找的。​​p>

              【讨论】:

                猜你喜欢
                • 2019-03-17
                • 2013-10-14
                • 2019-12-07
                • 1970-01-01
                • 1970-01-01
                • 2019-05-26
                • 2012-10-10
                • 2013-09-21
                • 2019-04-23
                相关资源
                最近更新 更多