﻿# 將 ASP.NET 的 SMTP 參數寫在 Web.Config 裡以簡化程式碼

以往我們發信都會將 SMTP Server 的 IP 位址設定在 web.config 的 appSettings 裡，所以在程式中可以很輕易的取得 SMTP Server 的 IP，不過當遇到 SMTP Server 需要登入時，就會需要修改程式碼，這樣頗為麻煩，因為可能網站內會發信的地方可能不少。

我們以往的作法，在發信時的程式如下：

```
SmtpClient smtp = new SmtpClient(
    System.Web.Configuration.WebConfigurationManager.AppSettings["SmtpHost"]);
smtp.Send(msg);
```

而需要輸入 SMTP 驗證的時候，就要明確指定 [SmtpClient](http://msdn.microsoft.com/zh-tw/library/system.net.mail.smtpclient.aspx) 的 [Credentials](http://msdn.microsoft.com/zh-tw/library/system.net.mail.smtpclient.credentials.aspx) 屬性，如下範例：

```
SmtpClient smtp = new SmtpClient(
    System.Web.Configuration.WebConfigurationManager.AppSettings["SmtpHost"]);
smtp.Credentials = new NetworkCredential("MyAccount", "ThisIsPassword");
smtp.Send(msg);
```

若是能將這些程式碼都能夠改成用宣告的方式移進去 web.config 的話，之後所有使用到 SmtpClient 的地方就不用費心設定了。以下這段範例是擺在 web.config 跟 <system.web> 相同階層的位置：

```
<system.net>
  <mailSettings>
    <smtp deliveryMethod="Network">
      <network defaultCredentials="false" 
        host="Your.SMTP.Server" port="25"
        userName="MyAccount" password="ThisIsPassword" />
    </smtp>
  </mailSettings>
</system.net>
```

加上去之後，程式碼就能簡化成以下程式碼，乾淨而清爽：

```
SmtpClient smtp = new SmtpClient();
smtp.Send(msg);
```

另外，若要手動取得 web.config 中的 mailSettings 設定值，可以參考以下程式：

```
Configuration config = 
    WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
MailSettingsSectionGroup settings = 
    (MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");
Response.Write("SMTP 主機: " + settings.Smtp.Network.Host + "<br />");
Response.Write("SMTP 埠號: " + settings.Smtp.Network.Port + "<br />");
Response.Write("SMTP 帳號: " + settings.Smtp.Network.UserName + "<br />");
Response.Write("SMTP 密碼: " + settings.Smtp.Network.Password + "<br />");
Response.Write("預設寄件者:" + settings.Smtp.From + "<br />");
```

**範例程式下載**

-   [SMTP\_Sample.zip (5.94 kb)](https://stwillblogassets.blob.core.windows.net/files/2011/11/SMTP_Sample.zip)

**相關連結**

-   [SmtpClient 類別](http://msdn.microsoft.com/zh-tw/library/system.net.mail.smtpclient.aspx)
-   [<mailSettings> 項目 (網路設定)](http://msdn.microsoft.com/zh-tw/library/w355a94k.aspx)
-   [<system.Net> 項目 (網路設定)](http://msdn.microsoft.com/zh-tw/library/6484zdc1.aspx)
-   [C# - 利用 Gmail SMTP 幫你寄信](https://dotblogs.com.tw/chhuang/2008/03/18/1815)
