萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

.NET 使用 SMTP 發送郵件 (含附件) 完整實作

前言

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 });

從 FileUpload 控制項直接附加 (Web Forms)

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 });
}

Gmail / Outlook 現代驗證注意事項

  • Gmail:必須開啟「兩步驟驗證」並產生「應用程式密碼」,不可使用主密碼。
  • Outlook / Office 365:建議改用 Microsoft Graph API (OAuth 2.0),SmtpClient 僅支援基本驗證,微軟已逐步淘汰。
  • 防火牆/連接埠:確保伺服器輸出 587 (TLS) 或 465 (SSL) 埠可達。

非同步發送 (避免阻塞 UI/執行緒)

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寄件者信箱不存在、被封鎖、或需驗證身分
copyright © 萬盛學電腦網 all rights reserved