我目前有一个像这样的 App.config:
<system.net>
<mailSettings>
<smtp from="xxx@xxnn.co.uk">
<network host="nn.nn.nn.nn"
port="25"
userName="myname"
password="mypass"/>
</smtp>
</mailSettings>
</system.net>
并使用以下方式发送 MailMessage 消息:
SmtpClient client = new SmtpClient();
try { client.Send(msg);
但是我如何配置 3 或 4 个不同的 <mailSettings>并在运行时引入正确的配置?
发送的邮箱会因row["Ledger"]而异下面
foreach (DataRow row in accounts.Tables[0].Rows)
{
string cust = row["Account"].ToString();
string site = row["Ledger"].ToString();
string mail = row["Email"].ToString();`
请您参考如下方法:
经过更多研究,我想出了以下解决方案: 在 App.Config 中
<configSections>
<sectionGroup name="Ledgers">
<section name="1stCompany" type="System.Configuration.NameValueSectionHandler" />
<section name="2ndCompany" type="System.Configuration.NameValueSectionHandler" />
<section name="3rdCompany" type="System.Configuration.NameValueSectionHandler" />
<section name="4thCompany" type="System.Configuration.NameValueSectionHandler" />
</sectionGroup>
</configSections>
<Ledgers>
<1stCompany>
<add key="host" value="nn.nn.nn.nn"/>
<add key="user" value="xxx1@xxx1.co.uk"/>
<add key="pass" value="password"/>
<add key="from" value="xxx1@xxx1.co.uk"/>
</1stCompany>
<2ndCompany>
<add key="host" value="nn.nn.nn.nn"/>
<add key="user" value="xxx2@xxx2.co.uk"/>
<add key="pass" value="password"/>
<add key="from" value="xxx2@xxx2.co.uk"/>
</2ndCompany>
<3rdCompany>
<add key="host" value="nn.nn.nn.nn"/>
<add key="user" value="xxx3@xxx3.co.uk"/>
................................. etc ...........
................................. etc .................
</Ledgers>
</configuration>
然后我编写了这个循环遍历 configSections 以匹配公司名称并引入邮件服务器设置的方法
private SmtpClient findClient(string site, ref string from)
{
// Get the application configuration file.
Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Get the collection of the section groups.
ConfigurationSectionGroupCollection myCollect = config.SectionGroups;
string host = "";
string user = "";
string pass = "";
SmtpClient client = new SmtpClient();
foreach (ConfigurationSectionGroup myGroups in myCollect)
{
if (myGroups.Name != "Ledgers") continue;
foreach (ConfigurationSection mySection in myGroups.Sections)
{
string ledger = mySection.SectionInformation.Name.ToString();
Console.WriteLine("Site is " + site + "ledger is " + ledger);
if (ledger.Equals(site, StringComparison.Ordinal))
{
var section = ConfigurationManager.GetSection(
mySection.SectionInformation.SectionName)
as NameValueCollection;
host = section["host"];
user = section["user"];
pass = section["pass"];
from = section["from"];
Console.WriteLine("\n\nHost " + host + "\nUsername " +
user + "\nPassword " + pass + "\nFrom " + from);
client.Port = 25;
client.Host = host;
client.Credentials = new System.Net.NetworkCredential(user, pass);
break;
}
}
}
return client;
}
类方法看起来比较费力。 我确信我可以直接转到所需的部分,因为我知道我需要哪个部分,因为它的标题与参数“站点”相匹配。 但它正在工作,所以现在没问题
