WebMail 幫助器封裝 SMTP 協定,提供簡潔 API 實現網頁表單郵件發送。本教學將建立完整的「支援請求」表單流程:輸入頁面 → 伺服器處理 → 郵件發送 → 結果回饋。
在網站根目錄 _AppStart.cshtml 設定 WebMail 屬性 (應用程式啟動自動執行):
@{
// 現有 WebSecurity 初始化 (若有)
WebSecurity.InitializeDatabaseConnection("Users", "UserProfile", "UserId", "Email", true);
// WebMail SMTP 設定
WebMail.SmtpServer = "smtp.example.com";
WebMail.SmtpPort = 587;
WebMail.EnableSsl = true;
WebMail.UserName = "support@example.com";
WebMail.Password = "your-app-password";
WebMail.From = "noreply@example.com";
}
屬性詳細說明:
true 強制加密傳輸,保護帳號密碼與郵件內容@{
Layout = "~/_Layout.cshtml";
Page.Title = "技術支援請求";
}
<!DOCTYPE html>
<html>
<head>
<title>@Page.Title</title>
</head>
<body>
<h1>Request for Assistance</h1>
<form method="post" action="Email_Send.cshtml">
<div>
<label for="customerEmail">Your Email:</label>
<input type="email" name="customerEmail" id="customerEmail" required />
</div>
<div>
<label for="customerRequest">Problem Details:</label>
<textarea name="customerRequest" id="customerRequest" cols="50" rows="6" required></textarea>
</div>
<p><input type="submit" value="Submit Request" /></p>
</form>
</body>
</html>
關鍵點:
action="Email_Send.cshtml":表單提交目標處理頁面method="post":使用 POST 方法傳送資料required:HTML5 瀏覽器端基本驗證type="email":瀏覽器自動驗證 Email 格式@{
Layout = "~/_Layout.cshtml";
Page.Title = "請求已送出";
// 讀取表單輸入
var customerEmail = Request["customerEmail"];
var customerRequest = Request["customerRequest"];
// 基本伺服器端驗證
if (String.IsNullOrEmpty(customerEmail) || String.IsNullOrEmpty(customerRequest)) {
<p class="error">請填寫所有必填欄位。</p>
} else {
try {
// 發送郵件至支援團隊
WebMail.Send(
to: "support-team@example.com",
subject: "支援請求 - " + customerEmail,
body: "來自: " + customerEmail + "\n\n問題描述:\n" + customerRequest,
isBodyHtml: false
);
<p class="success">您的支援請求已成功送出,我們將盡快回覆。</p>
} catch (Exception ex) {
// 生產環境應記錄日誌而非直接顯示
<p class="error">郵件發送失敗: @ex.Message</p>
// Log.Error(ex, "WebMail send failed for {Email}", customerEmail);
}
}
}
WebMail.Send(
to: "support@example.com",
subject: "支援請求 - " + customerEmail,
body: @<div>
<h2>新支援請求</h2>
<p><strong>來自:</strong> @customerEmail</p>
<p><strong>時間:</strong> @DateTime.Now</p>
<div style="background:#f5f5f5;padding:10px;">@customerRequest</div>
</div>,
isBodyHtml: true,
cc: "manager@example.com",
filesToAttach: new[] { Server.MapPath("~/App_Data/logs/latest.log") }
);
@using System.Diagnostics
@functions {
public static void LogEmailError(Exception ex, string email, string context) {
var eventLog = new EventLog("Application") { Source = "WebPagesApp" };
eventLog.WriteEntry(
$"WebMail Error | Context: {context} | Email: {email} | Error: {ex.Message}\nStack: {ex.StackTrace}",
EventLogEntryType.Error
);
}
}
try {
WebMail.Send(...);
} catch (SmtpException smtpEx) {
LogEmailError(smtpEx, customerEmail, "SMTP Protocol Error");
} catch (Exception ex) {
LogEmailError(ex, customerEmail, "General Error");
}