转自:http://www.cnblogs.com/hunanboy/archive/2006/09/25/514073.html
因为系统发邮件的老不稳定,所以需要把以前的代码升级一下,打开以前代码发现用的是1.1
版本的SmtpMail,系统开发用的是2005,MSDN上面则说明SmtpMail已经过时,而且通过资料和实
践也表明SmtpMail容易丢失邮件。原因就是这个类只能单线程同步操作。
2005里新引进SmtpClient类,属于System.Net.Mail命名空间下,2003里邮件操作类都是在
System.Web和System.Web.Mail里,而2005全部引入到了System.Net和System.Net.Mail命名空间
里了。
由于大部分属性和方法的说明在MSDN上都可以找到,也有现成的例子,所以我在这里不做过多的赘述。在这里只通过一个最简单的例子讨论一下最基本的属性和方法。
MSDN上写到,要使用SmtpClient进行邮件操作,需要指定MailMessage的From,To,Subject,Body等基本属性.
From:通俗点说法就是发邮件的
To:通俗点说就是发给谁
Subject:指邮件主题
Body:邮件内容
SmtpClient通过邮件服务器进行邮件操作肯定要牵涉到邮件服务器的端口,服务器,验证等操作,在此我推荐我认为在2005最简单和方便的操作方式,在2005里的配置文件里新加入了一些节点
我们的SmtpClient的这些服务器属性就可以通过以下形式而指定







host :邮件服务器地址
port:端口
userName:用户
password:密码
如此指定之后,在SmtpClient的Send方法里就会自动去匹配这些属性了。非常方便。
好,指定好这一步了,咱们的邮件发送就变的too Simple了。
请看以下代码

2

3

4

5

6

7

8

9

10

三行代码,就搞定邮件发送,是不是非常简单?呵呵。另外SmtpClient的一些其他的用法如发送附件、异步调用在此就不说了。因为这是最基本的说明文章,有兴趣学习的朋友可以去查阅MSDN。
依照此例写一个方法用于发送
{
//生成一个 使用SMTP发送邮件的客户端对象
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(strSmtpServer);
//表示以当前登录用户的默认凭据进行身份验证,不写依然能发送
//client.UseDefaultCredentials = true;
//包含用户名和密码
client.Credentials = new System.Net.NetworkCredential(UserName, Password);
//指定如何发送电子邮件。
//Network 电子邮件通过网络发送到 SMTP 服务器。
//PickupDirectoryFromIis 将电子邮件复制到挑选目录,然后通过本地 Internet 信息服务 (IIS) 传送。
//SpecifiedPickupDirectory 将电子邮件复制到 SmtpClient.PickupDirectoryLocation 属性指定的目录,然后由外部应用程序传送。
client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
//建立邮件对象
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(strFrom, strTo, strSubject, strBody);
//定义邮件正文,主题的编码方式
message.BodyEncoding = System.Text.Encoding.UTF8;
message.SubjectEncoding = System.Text.Encoding.UTF8;
//获取或设置一个值,该值指示电子邮件正文是否为 HTML。
message.IsBodyHtml = true;
//指定邮件优先级
message.Priority = System.Net.Mail.MailPriority.Normal;
//添加附件
//System.Web.Mail.MailAttachment mailAttachment=new System.Web.Mail.MailAttachment(@ "f:/baihe.txt ");
if (strFileName != " " && strFileName != null)
{
Attachment data = new Attachment(strFileName);
message.Attachments.Add(data);
}
//发件人身份验证,否则163 发不了
client.Credentials = new System.Net.NetworkCredential(strFrom, Password);
//发送
client.Send(message);
}