[ASP .NET]在web.config中透過sectionGroup紀錄多個email設定

[ASP .NET]在web.config中透過sectionGroup紀錄多個email設定

當系統有寄信需求時,我常用方式是將email設定寫在web.config中的appSettings一個一個寫各項設定

<appSettings>
  <add key="HinetMailAddress" value="test@msa.hinet.net" />
  <add key="HinetMailSmtp" value="msa.hinet.net" />
  <add key="HinetMailSmtpPswd" value="*******" />
  <add key="HinetMailSmtpPort" value="25" />
</appSettings>

然後程式再將每個設定一個個讀出來

string email = ConfigurationManager.AppSettings["HinetMailAddress"];
string smtp = ConfigurationManager.AppSettings["HinetMailSmtp"];
string smtppswd = ConfigurationManager.AppSettings["HinetMailSmtpPswd"];
string smtpport = ConfigurationManager.AppSettings["HinetMailSmtpPort"];

當有好幾個email設定時,appSettings就會設定很多行,感覺有點雜亂

此時可在web.config中用sectionGroup的方式一次設定好,設定方式如下:

<configuration>
  <configSections>
    <sectionGroup name="mailSettings">
      <section name="Hinet" type="System.Net.Configuration.SmtpSection"/>
      <section name="Gmail" type="System.Net.Configuration.SmtpSection"/>
    </sectionGroup>
  </configSections>
  <mailSettings>
    <Hinet deliveryMethod="Network" from="test@msa.hinet.net" >
      <network defaultCredentials="false"  enableSsl="true" host="msa.hinet.net" port="25"
        userName="test@msa.hinet.net" password="********"  />
    </Hinet>
    <Gmail deliveryMethod="Network" from="test@gmail.com" >
      <network defaultCredentials="false"  enableSsl="true" host="smtp.gmail.com" port="587"
        userName="test@gmail.com" password="****"  />
    </Gmail>
  </mailSettings>
</configuration>

程式中的使用方式如下:

SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("mailSettings/Hinet");

SmtpClient smtpClient = new SmtpClient(smtpSection.Network.Host, smtpSection.Network.Port);
smtpClient.Credentials = new NetworkCredential(smtpSection.From, smtpSection.Network.Password);
/*
UserName也可以從Newtwork取得
smtpClient.Credentials = new NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password);
*/
smtpClient.EnableSsl = smtpSection.Network.EnableSsl;

MailMessage mm = new MailMessage(smtpSection.From, "收件人email1;收件人email2");//多個收件人用;分隔即可
mm.Body = "郵件內容";
mm.Subject = "郵件抬頭";
smtpClient.Send(mm);
mm.Dispose();
sender = null;
smtpClient = null;

以上寄出的郵件,在寄件人會直接顯示email,有時候不容易分辨寄來的信是什麼作用,此時可以改以下方式讓收件者看到來信的單位為何:

MailAddress sender = new MailAddress(smtpSection.From, "想要顯示的寄件人文字");
MailMessage mm = new MailMessage(sender, "收件人email");

另外有時候要寄出多個收件者,又不想讓對方知道寄給誰,可以不直接給收件人,改用bcc的方式寄出:

MailAddress sender = new MailAddress(smtpSection.From, "寄件人");
MailMessage mm = new MailMessage();
mm.From = sender;
mm.Bcc.Add("收件人1");
mm.Bcc.Add("收件人2");
mm.Bcc.Add("收件人3");