Email.Send()bool 表示成敗using System;
using System.Net;
using System.Net.Mail;
using System.Text;
public static class Email
{
// 寄件人
public static string MailFrom { get; set; }
// 收件人陣列
public static string[] MailToArray { get; set; }
// 副本陣列
public static string[] MailCcArray { get; set; }
// 主旨
public static string MailSubject { get; set; }
// 內文
public static string MailBody { get; set; }
// 寄件人密碼
public static string MailPwd { get; set; }
// SMTP 主機
public static string Host { get; set; }
// SMTP 埠
public static int Port { get; set; }
// 是否 HTML
public static bool IsBodyHtml { get; set; }
// 附件路徑陣列
public static string[] AttachmentsPath { get; set; }
public static bool Send()
{
try
{
var fromAddr = new MailAddress(MailFrom);
var msg = new MailMessage { From = fromAddr };
if (MailToArray != null)
foreach (var to in MailToArray) msg.To.Add(to);
if (MailCcArray != null)
foreach (var cc in MailCcArray) msg.CC.Add(cc);
msg.Subject = MailSubject;
msg.SubjectEncoding = Encoding.UTF8;
msg.Body = MailBody;
msg.BodyEncoding = Encoding.Default;
msg.Priority = MailPriority.High;
msg.IsBodyHtml = IsBodyHtml;
if (AttachmentsPath != null && AttachmentsPath.Length > 0)
{
foreach (var path in AttachmentsPath)
msg.Attachments.Add(new Attachment(path));
}
using (var client = new SmtpClient(Host, Port))
{
client.Credentials = new NetworkCredential(MailFrom, MailPwd);
// client.EnableSsl = true; // 若需 SSL 取消註解
client.Send(msg);
}
return true;
}
catch (SmtpException ex)
{
// 可記錄 ex.Message 至 Log
return false;
}
}
}
Email.MailFrom = "sender@example.com";
Email.MailPwd = "password";
Email.Host = "smtp.example.com";
Email.Port = 587;
Email.IsBodyHtml = true;
Email.MailToArray = new[] { "a@test.com", "b@test.com" };
Email.MailCcArray = new[] { "cc@test.com" };
Email.MailSubject = "測試郵件";
Email.MailBody = "Hello
這是 HTML 郵件。
";
Email.AttachmentsPath = new[] { @"C:\report.pdf" };
bool ok = Email.Send();
Console.WriteLine(ok ? "發送成功" : "發送失敗");
| 需求 | 解法 |
|---|---|
| SSL/TLS | 設定 client.EnableSsl = true,Port 通常 587 或 465 |
| 大量收件人效能 | 改用 MailMessage.Bcc 或批次非同步發送 |
| 內嵌圖片 | 使用 AlternateView + LinkedResource |
| 非同步發送 | 改呼叫 client.SendMailAsync() 並回傳 Task<bool> |
| DKIM/SPF 簽署 | 需第三方庫 (如 MimeKit) 或郵件伺服器端設定 |