System.Net.Mail.SmtpClient 是 .NET 發送郵件的標準類別。本文示範基本寄信、帶附件、內嵌圖片、使用 Gmail SMTP 等常見場景,並說明安全性設定。
// Web.config / app.config
<appSettings>
<add key="SmtpServer" value="smtp.gmail.com" />
<add key="SmtpPort" value="587" />
<add key="EnableSsl" value="true" />
<add key="FromEmail" value="your@gmail.com" />
<add key="FromPassword" value="app-specific-password" /> <!-- Gmail 需應用程式密碼 -->
</appSettings>
// 共用發送方法
public static void SendEmail(string to, string subject, string body, bool isHtml = true, IEnumerable<Attachment> attachments = null)
{
var from = ConfigurationManager.AppSettings["FromEmail"];
var pwd = ConfigurationManager.AppSettings["FromPassword"];
var host = ConfigurationManager.AppSettings["SmtpServer"];
var port = int.Parse(ConfigurationManager.AppSettings["SmtpPort"]);
var ssl = bool.Parse(ConfigurationManager.AppSettings["EnableSsl"]);
using (var client = new SmtpClient(host, port))
{
client.EnableSsl = ssl;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(from, pwd);
using (var msg = new MailMessage(from, to, subject, body))
{
msg.IsBodyHtml = isHtml;
if (attachments != null)
foreach (var att in attachments) msg.Attachments.Add(att);
client.Send(msg);
}
}
}
// 檔案路徑附件
var att1 = new Attachment(@"C:\Reports\monthly.pdf");
att1.ContentDisposition.Inline = false; // 當作附件
// 內嵌圖片 (HTML 中用 <img src="cid:logo" /> 參考)
var att2 = new Attachment(@"C:\Images\logo.png");
att2.ContentId = "logo"; // 對應 cid:logo
att2.ContentDisposition.Inline = true;
SendEmail("target@example.com", "主旨", "<h1>內文</h1><img src='cid:logo' />", true, new[] { att1, att2 });
if (FileUpload1.HasFile)
{
var stream = FileUpload1.FileContent;
var contentType = FileUpload1.PostedFile.ContentType;
var fileName = Path.GetFileName(FileUpload1.FileName);
var att = new Attachment(stream, contentType);
att.Name = fileName;
att.ContentDisposition.FileName = fileName;
SendEmail(..., attachments: new[] { att });
}
SmtpClient 僅支援基本驗證,微軟已逐步淘汰。public static async Task SendEmailAsync(...)
{
using (var client = new SmtpClient(host, port)) { ... }
await client.SendMailAsync(msg); // .NET 4.5+
}
| 錯誤 | 原因與對策 |
|---|---|
| 5.7.0 Authentication Required | 密碼錯誤、未開啟應用程式密碼、或需允許「低安全性應用程式」 |
| Connection timed out | 防火牆阻擋、埠號錯誤、SSL/TLS 設定不符 |
| Mailbox unavailable | 寄件者信箱不存在、被封鎖、或需驗證身分 |