导航

  1. 常用CHM
  2. 订阅
  • 本站大部分内容从网上收集,收集目的仅供研究、学习。涉及版权或不希望收录您的文章请您及时与我联系。
  • 本站IM群,请自行选择。请各位朋友按照自己喜好加入。加入群后请及时发言,防止被清理。谢谢您的合作!!!
  • QQ群:Y①WEB开发(ASP.NET)号码:7351660 QQ群:Y②WEB开发(ASP+.NET)号码:11864905
  • QQ群:Y③WEB开发(DIV+CSS)号码:16610506 QQ群:Y④WEB开发(JS+AJAX)号码:16143998
  • QQ群:Y⑤WEB开发(新手)号码:12777715 MSN群:yaosansi[at]126.com
« LINQ -对付SQL Injection的"免费补洞策略"Visual Studio Add-Ins Every Developer Should Download Now »

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

分类: AJAX 发布: yaosansi 浏览: 日期: 2008年7月14日

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

相关文章:

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

Powered By Z-Blog 1.8 Walle Build 100427

Copyright 2005-2010 yaosansi'site All Rights Reserved.
感谢系统大玩家为本站提供FTP空间
辽ICP备05021434号