首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >App.config中的多个mailSettings

App.config中的多个mailSettings
EN

Stack Overflow用户
提问于 2015-06-26 21:27:11
回答 3查看 2.5K关注 0票数 2

我目前有一个App.config,如下所示:

代码语言:javascript
复制
<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消息:

代码语言:javascript
复制
SmtpClient client = new SmtpClient();
try { client.Send(msg);

但是如何配置3或4个不同的<mailSettings>并在运行时引入正确的配置呢?

根据下面的row["Ledger"],发送邮件的邮箱会有所不同

代码语言:javascript
复制
foreach (DataRow row in accounts.Tables[0].Rows)
{
    string cust = row["Account"].ToString();
    string site = row["Ledger"].ToString();
    string mail = row["Email"].ToString();`
EN

回答 3

Stack Overflow用户

发布于 2015-07-02 22:40:08

经过更多的研究,我想出了以下解决方案:在App.Config中

代码语言:javascript
复制
    <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来匹配公司名称并拉入邮件服务器设置

代码语言:javascript
复制
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;
    }

类方法看起来相当费力。我确信我可以直接转到所需的部分,因为我知道我需要哪个部分,因为它的标题与参数'site‘匹配。但是它正在工作,所以现在没问题。

票数 3
EN

Stack Overflow用户

发布于 2015-06-26 21:32:09

您可以在消息对象中指定发件人地址:

代码语言:javascript
复制
msg.From = new MailAddress("fred@somewhere.com");

因此,现在您需要关心的就是将site值映射到发件人电子邮件地址。例如,如果您将它们保存在app.configappSettings

代码语言:javascript
复制
<appSettings>
    <add key="Site1" value="someone@somewhere.com" />
    <add key="Site2" value="someone@somewhere-else.com" />
</appSettings>

你可以像这样得到它:

代码语言:javascript
复制
public string GetFromAddressBySite(string site)
{
    return ConfigurationManager.AppSettings[site];
}

例如,您的完整代码可能如下所示

代码语言:javascript
复制
SmtpClient client = new SmtpClient();

foreach (DataRow row in accounts.Tables[0].Rows)
{
    string cust = row["Account"].ToString();
    string site = row["Ledger"].ToString();
    string mail = row["Email"].ToString();

    //Get your email address, say, from the app.config file
    string fromAddress = GetFromAddressBySite(site);

    MailMessage msg = new MailMessage
    {
        From = new MailAddress(fromAddress),
        Subject = "Hello!",
        Body = "..."
    };

    msg.To.Add(new MailAddress(mail));

    client.Send(msg);
}

备注:您还可以将服务器主机、端口等存储在设置文件中,并使用它们:

代码语言:javascript
复制
var client = new SmtpClient("your.mailserver.com", 25);
票数 1
EN

Stack Overflow用户

发布于 2015-06-26 21:49:33

您不必从mailSettings获取您的设置。您可以使用自己的配置系统,例如JSON文件:

代码语言:javascript
复制
{
    "PublicEmailAddress" : { "From" : "external@mycompany.com" },
    "InternalEmailAddress": { "From" : "internal@mycompany.com"}
}

您将在启动时编写代码来读取配置并将配置存储在内存中,然后根据row["Ledger"]选择适当的配置。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31074443

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档