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

ASP.NET 發送 Email 完整範本:附件、優先權、HTML 格式與編碼

     編輯:關於ASP.NET

ASP.NET 1.x/2.0 使用 System.Web.Mail.SmtpMail 與 MailMessage 發送郵件(.NET 2.0+ 建議改用 System.Net.Mail 命名空間)。

基本發送流程

  1. 引用 System.Web.Mail 命名空間
  2. 建立 MailMessage 設定 From、To、Subject、Body、Priority、BodyFormat 等屬性
  3. 加入附件:mail.Attachments.Add(new MailAttachment(filePath))
  4. 設定 SMTP 伺服器:SmtpMail.SmtpServer = "smtp.example.com"
  5. 呼叫 SmtpMail.Send(mail)

完整範例 (VB.NET)

Imports System.Web.Mail

Dim mail As New MailMessage()
mail.From = "sender@example.com"
mail.To = "recipient@example.com"
mail.Subject = "測試郵件"
mail.Body = "<b>HTML 內容</b>"
mail.BodyFormat = MailFormat.Html
mail.Priority = MailPriority.High
mail.Fields.Add("https://schemas.microsoft.com/cdo/configuration/smtpserver", "smtp.example.com")
mail.Fields.Add("https://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1")
mail.Fields.Add("https://schemas.microsoft.com/cdo/configuration/sendusername", "user")
mail.Fields.Add("https://schemas.microsoft.com/cdo/configuration/sendpassword", "pass")

' 附件
mail.Attachments.Add(New MailAttachment(Server.MapPath("~/files/report.pdf")))

SmtpMail.Send(mail)

現代寫法

.NET 2.0 起請改用 System.Net.Mail.MailMessage、SmtpClient,支援 SSL、非同步發送、更豐富的編碼控制。

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