首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET 使用 SmtpClient 發送電子郵件完整範例

     編輯:ASP.NET 基礎

發送郵件是系統通知、驗證碼、密碼重設等常見功能。本文提供基於 System.Net.Mail.SmtpClient 的完整發送範例,以 QQ 郵箱 SMTP 為例,並說明關鍵設定與錯誤處理。

完整發送方法

public static void SendEmail(string from, string password, string to, string subject, string body, bool isHtml = true)
{
    using (var client = new SmtpClient())
    {
        // SMTP 伺服器設定(以 QQ 郵箱為例)
        client.Host = "smtp.qq.com";
        client.Port = 587; // 或 465 (SSL)
        client.EnableSsl = true; // QQ 郵箱需啟用 SSL
        client.UseDefaultCredentials = false;
        client.Credentials = new NetworkCredential(from, password);
        client.DeliveryMethod = SmtpDeliveryMethod.Network;

        using (var message = new MailMessage(from, to))
        {
            message.Subject = subject;
            message.Body = body;
            message.BodyEncoding = Encoding.UTF8;
            message.IsBodyHtml = isHtml;

            try
            {
                client.Send(message);
                // 記錄成功日誌
            }
            catch (SmtpException ex)
            {
                // 記錄詳細錯誤:ex.StatusCode, ex.Message
                throw new InvalidOperationException("郵件發送失敗", ex);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("郵件發送發生未預期錯誤", ex);
            }
        }
    }
}

呼叫範例

SendEmail(
    from: "your_account@qq.com",
    password: "your_authorization_code", // 注意:非登入密碼,需在郵箱開啟 SMTP 取得授權碼
    to: "recipient@example.com",
    subject: "測試郵件主旨",
    body: "<h1>這是 HTML 內容</h1><p>支援中文顯示。</p>");

關鍵設定說明

屬性說明
HostSMTP 伺服器位址(如 smtp.qq.com、smtp.gmail.com、smtp.office365.com)
Port常用:587 (STARTTLS)、465 (SSL 隱性)、25 (無加密,不建議)
EnableSsl是否使用 SSL/TLS 加密,主流郵箱皆需設為 true
Credentials帳號與密碼/授權碼,UseDefaultCredentials 必須設為 false
IsBodyHtml郵件內容是否為 HTML 格式

常見問題與解決

  • 驗證失敗:確認是否使用「授權碼」而非登入密碼;檢查郵箱是否開啟 SMTP/IMAP 服務。
  • 連線逾時:檢查防火牆、網路連通性、Port 是否正確;嘗試 telnet smtp.qq.com 587 測試。
  • 中文亂碼:確保 BodyEncoding = Encoding.UTF8,且 Subject 若含中文需進行 MIME 編碼(MailMessage 內建處理)。
  • 大量發送:單一連線重複發送以減少握手開銷;考慮使用專業郵件服務(SendGrid、Mailgun、Amazon SES)提高送達率。

非同步發送(建議生產環境)

public static async Task SendEmailAsync(string from, string password, string to, string subject, string body, bool isHtml = true)
{
    using (var client = new SmtpClient())
    {
        client.Host = "smtp.qq.com";
        client.Port = 587;
        client.EnableSsl = true;
        client.UseDefaultCredentials = false;
        client.Credentials = new NetworkCredential(from, password);

        using (var message = new MailMessage(from, to))
        {
            message.Subject = subject;
            message.Body = body;
            message.BodyEncoding = Encoding.UTF8;
            message.IsBodyHtml = isHtml;

            await client.SendMailAsync(message);
        }
    }
}

非同步版本避免阻塞請求執行緒,提升 Web 應用回應速度。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved