Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
479 views
in Technique[技术] by (71.8m points)

c# - Setting multiple SMTP settings in web.config?

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/mailSettings approach, but as I understand it, that only allows one SMTP connection definition at a time, used by SmtpClient().

However, I need more of a connectionStrings-like approach, where I can pull a set of settings based on a key/name.

Any recommendations? I'm open to skipping the tradintional SmtpClient/mailSettings approach, and I think will have to...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I needed to have different smtp configurations in the web.config depending on the environment: dev, staging and production.

Here's what I ended up using:

In 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="[email protected]">
      <network host="..." defaultCredentials="false"/>
    </smtp_1>
    <smtp_2 deliveryMethod="Network" from="[email protected]">
      <network host="1..." defaultCredentials="false"/>
    </smtp_2>
    <smtp_3 deliveryMethod="Network" from="[email protected]">
      <network host="..." defaultCredentials="false"/>
    </smtp_3>
  </mailSettings>
</configuration>

Then in code:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...