在 ASP.NET 應用程式中發送電子郵件是常見需求。雖然 .NET Framework 早期提供 `System.Web.Mail`,但已標記為過時,建議改用 `System.Net.Mail` 命名空間。本文提供一個封裝良好的 `MailHelper` 類別,支援收件人、抄送、密送、附件、HTML 內容、SMTP 驗證等功能,並附上完整的前後台整合範例。
using System;
using System.Net.Mail;
using System.Net;
public class MailHelper
{
///
/// 發送電子郵件
///
/// 收件人,多個以 ; 分隔
/// 寄件人信箱
/// 寄件人密碼或應用程式密碼
/// 抄送
/// 密送
/// 主旨
/// 附件實體路徑,可為空
/// 郵件內容(支援 HTML)
/// SMTP 伺服器,預設自動推斷 smtp.域名
/// 連接埠,預設 587 (STARTTLS)
/// 是否啟用 SSL
/// 成功回傳 true,失敗拋出例外
public static bool SendMail(
string to, string from, string password,
string cc, string bcc, string subject,
string attachmentPath, string body,
string smtpServer = "", int port = 587, bool enableSsl = true)
{
try
{
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(from);
foreach (string addr in to.Split(new[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries))
mail.To.Add(addr.Trim());
if (!string.IsNullOrWhiteSpace(cc))
foreach (string addr in cc.Split(new[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries))
mail.CC.Add(addr.Trim());
if (!string.IsNullOrWhiteSpace(bcc))
foreach (string addr in bcc.Split(new[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries))
mail.Bcc.Add(addr.Trim());
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true; // 支援 HTML 內容
mail.BodyEncoding = System.Text.Encoding.UTF8;
if (!string.IsNullOrWhiteSpace(attachmentPath) && System.IO.File.Exists(attachmentPath))
{
Attachment attachment = new Attachment(attachmentPath);
mail.Attachments.Add(attachment);
}
// 自動推斷 SMTP 伺服器
if (string.IsNullOrWhiteSpace(smtpServer))
{
int atIndex = from.LastIndexOf('@');
if (atIndex > 0)
smtpServer = "smtp." + from.Substring(atIndex + 1);
}
using (SmtpClient client = new SmtpClient(smtpServer, port))
{
client.Credentials = new NetworkCredential(from, password);
client.EnableSsl = enableSsl;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Timeout = 30000; // 30 秒逾時
client.Send(mail);
}
}
return true;
}
catch (SmtpException ex)
{
// 記錄詳細錯誤日誌
System.Diagnostics.Debug.WriteLine($"SMTP 錯誤: {ex.StatusCode} - {ex.Message}");
throw; // 向上拋出讓呼叫端處理
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"發送郵件失敗: {ex.Message}");
throw;
}
}
}
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Mail.aspx.cs" Inherits="MailDemo" ValidateRequest="false" %>
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title>發送郵件測試</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.3/dist/jquery.validate.min.js"></script>
<script type="text/javascript">
function setFilePath() {
var fileVal = document.getElementById("File1").value;
document.getElementById("HiddenField1").value = fileVal;
}
</script>
</head>
<body>
<form id="form1" runat="server" enctype="multipart/form-data">
<div style="max-width:600px;margin:20px auto;font-family:Microsoft JhengHei;">
<h3>發送郵件測試表單</h3>
<div class="form-group">
<label>收件人:</label>
<asp:TextBox ID="txtTo" runat="server" CssClass="form-control" placeholder="多個以 ; 分隔"></asp:TextBox>
</div>
<div class="form-group">
<label>抄送:</label>
<asp:TextBox ID="txtCc" runat="server" CssClass="form-control" placeholder="多個以 ; 分隔"></asp:TextBox>
</div>
<div class="form-group">
<label>密送:</label>
<asp:TextBox ID="txtBcc" runat="server" CssClass="form-control" placeholder="多個以 ; 分隔"></asp:TextBox>
</div>
<div class="form-group">
<label>主旨:</label>
<asp:TextBox ID="txtSubject" runat="server" CssClass="form-control"></asp:TextBox>
</div>
<div class="form-group">
<label>內容 (支援 HTML):</label>
<asp:TextBox ID="txtBody" runat="server" TextMode="MultiLine" Rows="6" CssClass="form-control"></asp:TextBox>
</div>
<div class="form-group">
<label>附件:</label>
<input id="File1" type="file" onchange="setFilePath()" />
<asp:HiddenField ID="HiddenField1" runat="server" />
</div>
<asp:Button ID="btnSend" runat="server" Text="發送郵件" CssClass="btn btn-primary" OnClick="btnSend_Click" OnClientClick="setFilePath();" />
<asp:Label ID="lblResult" runat="server" CssClass="text-danger mt-2"></asp:Label>
</div>
</form>
</body>
</html>
public partial class MailDemo : System.Web.UI.Page
{
protected void btnSend_Click(object sender, EventArgs e)
{
try
{
string attachmentPath = HiddenField1.Value;
// 注意:HTML input type=file 的 value 僅含檔名,無法直接取得伺服器路徑
// 實務上應先將檔案上傳至伺服器暫存資料夾,再取得實體路徑傳給 MailHelper
// 此處為示範,假設已上傳並取得完整路徑
string fullAttachmentPath = string.IsNullOrWhiteSpace(attachmentPath) ? "" : Server.MapPath("~/TempUploads/") + System.IO.Path.GetFileName(attachmentPath);
bool success = MailHelper.SendMail(
to: txtTo.Text.Trim(),
from: "your_email@gmail.com", // 替換為實際寄件信箱
password: "your_app_password", // 使用應用程式密碼或真實密碼
cc: txtCc.Text.Trim(),
bcc: txtBcc.Text.Trim(),
subject: txtSubject.Text.Trim(),
attachmentPath: fullAttachmentPath,
body: txtBody.Text
);
if (success)
lblResult.Text = "郵件發送成功!";
else
lblResult.Text = "郵件發送失敗,請檢查設定。";
}
catch (Exception ex)
{
lblResult.Text = $"發送失敗:{ex.Message}";
// 記錄完整堆疊追蹤至日誌系統
}
}
}
前端 `` 的 `value` 屬性僅包含檔案名稱(如 `C:\fakepath\test.pdf`),無法直接作為附件路徑。實際開發流程應為:
若郵件發送耗時較長,建議使用 `SmtpClient.SendMailAsync` 搭配 `async/await`,或將發送工作排入背景工作佇列(如 Hangfire、Quartz.NET),避免網頁回應逾時。
若需豐富文字編輯,可整合 CKEditor、TinyMCE 或 Summernote,並確保 `mail.BodyEncoding = Encoding.UTF8`,避免中文亂碼。
總結:本文提供一個功能完整、可直接套用的 `MailHelper` 元件,涵蓋 SMTP 驗證、SSL、多收件人、附件、HTML 內容等實務需求,並說明前端檔案上傳與附件路徑處理的關鍵細節。開發者可依專案需求調整參數、加入日誌記錄、重試機制或佇列化發送,構建穩健的郵件通知系統。