简体   繁体   English

App.config中的多个mailSettings

[英]Multiple mailSettings in App.config

I currently have an App.config like so: 我目前有一个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>

And send MailMessage msg using: 并使用以下命令发送MailMessage消息:

SmtpClient client = new SmtpClient();
try { client.Send(msg);

But how do I configure 3 or 4 different <mailSettings> and pull in the correct configuration at run time? 但是,如何配置3或4个不同的<mailSettings>并在运行时提取正确的配置?

The mailbox to send FROM will vary depending on row["Ledger"] below 要发送自的邮箱将根据下面的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();`

Well after a bit more research i came up with the following solution: in App.Config 经过更多研究之后,我想到了以下解决方案:在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>

Then I wrote this method which loops through configSections to match the company names and pull in the mailserver settings 然后,我编写了此方法,该方法遍历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;
    }

The class method seems rather laborious. 类方法似乎很费力。 I am sure I could go straight to the required section because I know which section I need because it's heading matches the parameter 'site'. 我确定我可以直接进入必填部分,因为我知道我需要哪一部分,因为其标题与参数“ site”相匹配。 But it is working so is fine for now 但是它正在工作,所以现在很好

You can specify the from address in the message object: 您可以在消息对象中指定发件人地址:

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

So now all you need to worry about is mapping the site value to a from email address. 因此,现在您只需要担心将site值映射到发件人的电子邮件地址。 For example if you keep them in the appSettings of your app.config : 例如,如果将它们保留在app.configappSettings中:

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

You can get it like this: 您可以这样获得:

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

As an example, your full code might look like this 例如,您的完整代码可能如下所示

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

Note : You can also store server host, port etc. in a settings file and use them too: 注意 :您还可以将服务器主机,端口等存储在设置文件中,也可以使用它们:

var client = new SmtpClient("your.mailserver.com", 25);

You don't have to pick up your settings from mailSettings . 您不必从mailSettings设置。 You could use your own configuration system, such as a JSON file: 您可以使用自己的配置系统,例如JSON文件:

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

You'd write code on startup to read in the configuration and store the configuration in memory, then select the appropriate one based on row["Ledger"] . 您将在启动时编写代码以读取配置并将配置存储在内存中,然后根据row["Ledger"]选择合适的配置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM