System.Net.Mail.SmtpClient 是 .NET 發送郵件的標準工具。本文提供支援 SSL、附件、HTML/純文字、編碼指定、優先級設定的完整通用方法,並列出常用郵件服務商 SMTP 設定。
| 服務商 | SMTP 位址 | 埠號 (SSL) | 備註 |
|---|---|---|---|
| Gmail | smtp.gmail.com | 587 (STARTTLS) / 465 (SSL) | 需開啟「低安全性應用程式」或應用程式密碼 |
| Outlook/Hotmail | smtp.office365.com | 587 | 同 Gmail |
| 163/126 | smtp.163.com / smtp.126.com | 465 / 994 | 需開啟 SMTP 服務並設定授權碼 |
| smtp.qq.com | 465 / 587 | 需開啟 SMTP 並獲取授權碼 | |
| Yahoo | smtp.mail.yahoo.com | 465 / 587 | 需開啟「不安全應用程式」存取 |
using System;
using System.Net;
using System.Net.Mail;
using System.Text;
public static class MailHelper
{
public static void SendEmail(
string fromEmail, string fromPassword,
string toEmail, string smtpHost, int smtpPort,
string subject, string body,
bool enableSsl = true,
bool isBodyHtml = false,
string[] attachments = null,
Encoding bodyEncoding = null,
MailPriority priority = MailPriority.Normal)
{
// 發件人/收件人
var from = new MailAddress(fromEmail);
var to = new MailAddress(toEmail);
using var message = new MailMessage(from, to);
// 主旨、內容、編碼
message.Subject = subject;
message.Body = body;
message.IsBodyHtml = isBodyHtml;
message.BodyEncoding = bodyEncoding ?? Encoding.UTF8;
message.SubjectEncoding = message.BodyEncoding;
message.Priority = priority;
// 附件
if (attachments != null)
{
foreach (string file in attachments)
{
if (File.Exists(file))
message.Attachments.Add(new Attachment(file));
}
}
// SMTP 客戶端
using var client = new SmtpClient(smtpHost, smtpPort)
{
EnableSsl = enableSsl,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(
fromEmail.Contains('@') ? fromEmail.Substring(0, fromEmail.IndexOf('@')) : fromEmail,
fromPassword),
DeliveryMethod = SmtpDeliveryMethod.Network,
Timeout = 30000 // 30 秒
};
try
{
client.Send(message);
Console.WriteLine("郵件發送成功");
}
catch (SmtpException ex)
{
Console.WriteLine($"SMTP 錯誤: {ex.StatusCode} - {ex.Message}");
throw;
}
catch (Exception ex)
{
Console.WriteLine($"發送失敗: {ex.Message}");
throw;
}
}
}
// 163 郵箱發送 HTML 郵件含附件
MailHelper.SendEmail(
fromEmail: "your@163.com",
fromPassword: "你的授權碼", // 非登入密碼
toEmail: "target@example.com",
smtpHost: "smtp.163.com",
smtpPort: 465,
subject: "測試郵件",
body: "你好
這是 HTML 郵件
",
enableSsl: true,
isBodyHtml: true,
attachments: new[] { @"C:\report.pdf", @"C:\image.png" },
priority: MailPriority.High
);
SmtpClient,避免頻繁建立 TCP 連線;考慮使用郵件佇列 (如 Hangfire) 非同步發送。SmtpClient 已標記過時 (Obsolete),官方建議改用 MailKit (MimeKit) 套件,功能更強且跨平台。client.SendMailAsync(message) 避免阻塞 UI 執行緒。
// NuGet: MailKit
using MailKit.Net.Smtp;
using MimeKit;
var message = new MimeMessage();
message.From.Add(new MailboxAddress("發件人", "your@163.com"));
message.To.Add(new MailboxAddress("收件人", "target@example.com"));
message.Subject = "測試";
message.Body = new TextPart("html") { Text = "你好
" };
using var client = new SmtpClient();
await client.ConnectAsync("smtp.163.com", 465, true); // SSL
await client.AuthenticateAsync("your@163.com", "授權碼");
await client.SendAsync(message);
await client.DisconnectAsync(true);
掌握 SmtpClient 基礎用法並了解 MailKit 現代替代方案,讓 C# 發送郵件功能穩健、可維護、跨平台。