從.NET 2.0 開始,引入了一個新的類,System.Net.Mail.MailMessage。該類用來取代 .NET 1.1 時代System.Web.Mail.MailMessage類。System.Net.Mail.MailMessage 類用於指定一個郵件,另外一個類 System.Net.Mail.SmtpClient 則用來設置 SMTP,然後發送郵件。由於目前 SMTP 都需要進行身份驗證,有的還需要 SSL(比如GMail),所以設置的屬性稍微多一些。代碼片斷如下:
using System.Net.Mail;
MailMessage mailMsg = new MailMessage();
mailMsg.From = new MailAddress("你的email地址");
mailMsg.To.Add("接收人1的email地址");
mailMsg.To.Add("接收人2的email地址");
mailMsg.Subject = "郵件主題";
mailMsg.Body = "郵件主體內容";
mailMsg.BodyEncoding = Encoding.UTF8;
mailMsg.IsBodyHtml = false;
mailMsg.Priority = MailPriority.High;
SmtpClient smtp = new SmtpClient();
// 提供身份驗證的用戶名和密碼
// 網易郵件用戶可能為:username password
// Gmail 用戶可能為:username@gmail.com password
smtp.Credentials = new NetworkCredential("用戶名", "密碼");
smtp.Port = 25; // Gmail 使用 465 和 587 端口
smtp.Host = "SMTP 服務器地址"; // 如 smtp.163.com, smtp.gmail.com smtp.EnableSsl = false; // 如果使用GMail,則需要設置為true smtp.SendCompleted += new SendCompletedEventHandler(SendMailCompleted);
try {
smtp.SendAsync(mailMsg, mailMsg);
} catch (SmtpException ex) {
Console.WriteLine(ex.ToString());
}
...
void SendMailCompleted(object sender, AsyncCompletedEventArgs e) { MailMessage mailMsg = (MailMessage)e.UserState;
string subject = mailMsg.Subject;
if (e.Cancelled) // 郵件被取消
{
Console.WriteLine(subject + " 被取消。");
}
if (e.Error != null)
{
Console.WriteLine("錯誤:" + e.Error.ToString());
} else
{
Console.WriteLine("發送完成。");
}
}