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

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

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

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

最佳答案

根据环境,我需要在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");

关于c# - 在web.config中设置多个SMTP设置?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4363038/

10-17 00:06