App.config中的多个mailSettings

时间:2015-06-26 13:27:11

标签: c#

我目前有一个像这样的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>并在运行时提供正确的配置?

发送FROM的邮箱会因下面的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();`

3 个答案:

答案 0 :(得分:2)

经过一番研究后,我想出了以下解决方案: 在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;
    }

班级方法似乎相当费力。 我确信我可以直接进入所需的部分,因为我知道我需要哪个部分,因为它的标题与参数'site'匹配。 但它正在工作,所以现在很好

答案 1 :(得分:1)

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

msg.From = new MailAddress("fred@somewhere.com");

所以现在您需要担心的是将site值映射到来自电子邮件地址。例如,如果您将它们保留在appSettings的{​​{1}}中:

app.config

你可以这样:

<appSettings>
    <add key="Site1" value="someone@somewhere.com" />
    <add key="Site2" value="someone@somewhere-else.com" />
</appSettings>

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

public string GetFromAddressBySite(string site)
{
    return ConfigurationManager.AppSettings[site];
}

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

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);
}

答案 2 :(得分:1)

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

{
    "PublicEmailAddress" : { "From" : "external@mycompany.com" },
    "InternalEmailAddress": { "From" : "internal@mycompany.com"}
}

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