功能特色
- SMTP 發送、SSL/TLS 加密
- HTML/純文字郵件、自訂編碼 (預設 UTF-8)
- 多收件人、抄送 (CC)、密件副本 (BCC)
- 附件支援 (單一/多檔)
- 不發送郵件驗證帳密 (POP3 非同步檢查)
- 簡潔流暢 API:鏈式設定 + 單一方法發送
使用範例
var mail = new MailSmtp("smtp.qq.com", "1215247044", "password")
.SetIsHtml(true)
.SetEncoding(Encoding.UTF8)
.SetIsSSL(true)
.SetCC("cc1@qq.com", "cc2@qq.com")
.SetBCC("bcc@qq.com");
bool ok = mail.Send(
from: "1215247044@qq.com",
senderName: "測試系統",
to: "610262374@qq.com",
subject: "測試主旨",
body: "測試內容",
attachment: Server.MapPath("~/Test.dll")
);
Console.WriteLine(mail.Result); // 發送結果訊息
核心類別結構 (節錄)
public class MailSmtp
{
private readonly SmtpClient _smtp = new SmtpClient();
private Encoding _encoding = Encoding.UTF8;
private bool _isHtml = true;
private string[] _cc, _bcc;
public string Result { get; private set; }
public MailSmtp(string host, string user, string pass) {
_smtp.Host = host;
_smtp.Port = 25; // 0x19
_smtp.EnableSsl = false;
if (!string.IsNullOrEmpty(user) && !string.IsNullOrEmpty(pass))
_smtp.Credentials = new NetworkCredential(user, pass);
}
// 流暢設定器
public MailSmtp SetEncoding(Encoding e) { _encoding = e; return this; }
public MailSmtp SetIsHtml(bool b) { _isHtml = b; return this; }
public MailSmtp SetCC(params string[] cc) { _cc = cc; return this; }
public MailSmtp SetBCC(params string[] bcc) { _bcc = bcc; return this; }
public MailSmtp SetIsSSL(bool ssl) { _smtp.EnableSsl = ssl; return this; }
public bool Send(string from, string sender, string to, string subject, string body, string attachment = null) {
try {
var msg = new MailMessage {
From = new MailAddress(from, sender, _encoding),
Subject = subject,
Body = body,
IsBodyHtml = _isHtml,
BodyEncoding = _encoding,
SubjectEncoding = _encoding,
};
msg.To.Add(to);
if (_cc != null) foreach (var c in _cc) msg.CC.Add(c);
if (_bcc != null) foreach (var b in _bcc) msg.Bcc.Add(b);
if (!string.IsNullOrEmpty(attachment))
msg.Attachments.Add(new Attachment(attachment));
_smtp.Send(msg);
Result = "發送成功";
return true;
}
catch (Exception ex) {
Result = $"發送失敗: {ex.Message}";
return false;
}
}
// 非同步驗證帳密 (POP3)
public void ValidateCredentialsAsync(Action callback) { ... }
}
設計亮點
- 流暢介面 (Fluent Interface) 讓設定鏈式可讀
- 預設值合理 (UTF-8、HTML、Port 25)
- 例外內部捕獲,回傳
bool + Result 字串,呼叫端無需 try-catch
- 非同步驗證避免 UI 凍結 (原文使用
ThreadPool,現代建議 async/await)
現代化建議
- 改用
MailKit (跨平台、支援 OAuth2、IMAP/POP3/SMTP 完整)
SmtpClient 在 .NET Core 已過時,官方推薦 MailKit
- 非同步方法改為
Task<bool> SendAsync(...)
- 依賴注入註冊
IMailService 介面