我有一个简单的应用程序,可以向我们的一些内部用户发送状态电子邮件。
我使用一个简单的应用程序配置文件 (App.config) 来存储有关预期用户的电子邮件地址和姓名信息。由于 appSettings 部分似乎只支持简单的键/值对,它目前看起来像这样:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="toName" value="Recipient Name" />
<add key="toAddr" value="some@email.com" />
<add key="toName2" value="Another Recipient Name" />
<add key="toAddr2" value="another@email.com" />
<add key="ccName" value="An Archive"/>
<add key="ccAddr" value="copies@email.com"/>
<add key="ccName2" value="Another Archive"/>
<add key="ccAddr2" value="morecopies@email.com"/>
</appSettings>
</configuration>
然后我在代码中单独添加每个收件人。
目前,这意味着每次添加或删除收件人时,我还需要重写代码来处理新的收件人并重新构建和重新部署应用程序
我希望能够存储自定义配置条目,例如:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<recipients>
<recipient recType="to" recAddr="some@email.com" recName="Recipient Name" />
<recipient recType="to" recAddr="another@email.com" recName="Another Recipient Name" />
<recipient recType="cc" recAddr="copies@email.com" recName="An Archive"/>
<recipient recType="cc" recAddr="morecopies@email.com" recName="Another Archive"/>
</recipients>
</configuration>
所以我可以遍历它们:
MailMessage message = new MailMessage();
foreach(recipient rec in recipients)
{
MailAddress mailAddress = new MailAddress(recipient["recAddr"],recipient["recName"]);
if(recipient["recType"] == "cc")
message.CC.Add(mailAddress);
else
message.To.Add(mailAddress);
}
如何做到这一点?
回答: 使用 Regfor 链接中的示例,我能够构建一个自定义配置部分,其中包含一组自定义 ConfigurationElement,如下所示:
public class RecipientElement : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true, IsKey = true)]
public string Name
{
get
{
return (string)base["name"];
}
}
[ConfigurationProperty("mailAddr", IsRequired = true)]
public string Address
{
get
{
return (string)base["mailAddr"];
}
}
[ConfigurationProperty("isCC")]
public bool IsCC
{
get
{
return (bool)base["isCC"];
}
}
}
最后的配置部分:
<recipientSection>
<recipients>
<recipient name="Primary recipient" mailAddr="usermailbox@email.com" isCC="false" />
<recipient name="Archive" mailAddr="copies@email.com" isCC="true" />
</recipients>
</recipientSection>
循环浏览recipients
集合让我可以添加尽可能多的收件人,因为 SmtpClient 会让我发送到:)
多谢你们