WebMail 物件封裝 SMTP 協定,提供簡潔 API 讓 Web Pages 輕鬆發送電子郵件,支援 SSL、附件、HTML 郵件、抄送等企業級功能。
| 屬性 | 型別 | 描述 | 必要性 |
|---|---|---|---|
| SmtpServer | String | SMTP 伺服器主機名稱 (如 smtp.gmail.com) | 必要 |
| SmtpPort | Int | SMTP 連接埠 (標準 25、SSL 465、TLS 587) | 必要 |
| EnableSsl | Boolean | 啟用 SSL/TLS 加密傳輸 | 建議 true |
| UserName | String | SMTP 驗證帳號 (通常為完整 Email) | 必要 |
| Password | String | SMTP 驗證密碼 (或應用程式專用密碼) | 必要 |
| From | String | 寄件人顯示 Email (通常同 UserName) | 必要 |
| 參數 | 型別 | 必要 | 描述 |
|---|---|---|---|
| to | String | 是 | 收件人 Email,多筆以分號 ; 分隔 |
| subject | String | 是 | 郵件主旨 |
| body | String | 是 | 郵件內文 |
| from | String | 否 | 覆蓋預設寄件人 |
| cc | String | 否 | 副本收件人,分號分隔 |
| filesToAttach | Collection | 否 | 附件檔案路徑集合 |
| isBodyHtml | Boolean | 否 | true 為 HTML 格式內文,false 為純文字 (預設) |
| additionalHeaders | Collection | 否 | 額外郵件標頭 (如 Reply-To、X-Priority) |
| 項目 | 值 |
|---|---|
| 類別完整名稱 | System.Web.Helpers.WebMail |
| 命名空間 | System.Web.Helpers |
| 組件 | System.Web.Helpers.dll |
在網站根目錄建立 _AppStart.cshtml (若不存在),應用程式啟動時自動執行:
@{
WebMail.SmtpServer = "smtp.example.com";
WebMail.SmtpPort = 587; // TLS 標準埠
WebMail.EnableSsl = true; // 強制加密
WebMail.UserName = "noreply@example.com";
WebMail.Password = "your-app-password"; // 使用應用程式專用密碼
WebMail.From = "noreply@example.com";
}
關鍵設定說明:
注意: _AppStart 中初始化屬性後,呼叫 WebMail.Send() 前無需重複設定,除非需動態覆蓋特定郵件參數。
| 服務商 | SMTP Server | Port | SSL/TLS | 備註 |
|---|---|---|---|---|
| Gmail | smtp.gmail.com | 587 | STARTTLS | 需啟用 2FA + 應用程式密碼 |
| Outlook/Office365 | smtp.office365.com | 587 | STARTTLS | 支援現代驗證 OAuth2 |
| SendGrid | smtp.sendgrid.net | 587 | STARTTLS | API Key 作為密碼 |
| Mailgun | smtp.mailgun.org | 587 | STARTTLS | API Key 作為密碼 |
| 自架 Postfix | mail.yourdomain.com | 587/25 | STARTTLS | 需正確設定 SPF/DKIM/DMARC |
@functions {
public static async Task<bool> SendAsync(string to, string subject, string body, bool isHtml = true) {
try {
WebMail.Send(to: to, subject: subject, body: body, isBodyHtml: isHtml);
return true;
} catch (Exception ex) {
// 記錄日誌: Log.Error(ex, "Email send failed to {To}", to);
return false;
}
}
}
生產環境建議:使用背景工作服務 (Hangfire、Quartz、IHostedService) 佇列發送,避免封鎖 HTTP 要求執行緒;整合 Serilog/NLog 記錄發送狀態;實作重試機制與死信佇列。