使用 System.Net.Mail.MailMessage 发送电子邮件

从.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("发送完成。");
    }
}

posted @ 2008-01-06 22:45  Mr. Zhang  阅读(6283)  评论(6编辑  收藏  举报