簡體   English   中英

App.config中的多個mailSettings

[英]Multiple mailSettings in App.config

我目前有一個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;
    }

類方法似乎很費力。 我確定我可以直接進入必填部分,因為我知道我需要哪一部分,因為其標題與參數“ site”相匹配。 但是它正在工作,所以現在很好

您可以在消息對象中指定發件人地址:

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

因此,現在您只需要擔心將site值映射到發件人的電子郵件地址。 例如,如果將它們保留在app.configappSettings中:

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

注意 :您還可以將服務器主機,端口等存儲在設置文件中,也可以使用它們:

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

您不必從mailSettings設置。 您可以使用自己的配置系統,例如JSON文件:

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

您將在啟動時編寫代碼以讀取配置並將配置存儲在內存中,然后根據row["Ledger"]選擇合適的配置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM