记得原来在.Net 1.X中编写发送邮件的代码是使用操作系统的CDO组件中的CDO.Message来来实现的,因为这个里面可以实现SMTP服务器认证等一序列的发送邮件的详细功能,不过不管是什么错误都会提示是CDO.Message对象无法访问或其它的CDO.Message异常,而在.Net Framework 1.X的FCL(Framework Class Library)中提供的System.Web.Mail.SmtpMail类实现发送邮件的功能十分Simple,连SMTP服务器认证的功能都不提供,真的够晕。
不过到了.Net Framework 2.0中System.Web.Mail.SmtpMail的SDK说明的第一行已经就明确标明了红色的粗体字“注意:此类现在已过时。”,看来这个类确实是.Net Framework 1.X设计问题,可能也是过度类了。
在.Net Framework 2.0中取而代之的是System.Net.Mail命名空间下的类,其发送邮件的功能已经被设计得Very good了。我的做法喜欢先深入后浅出,首先让我们来看看在.Net 2.0中如何完全用代码来实现发送最简单的邮件(无需SMTP认证)。
string
mailServerName
=
"
mail.powerise.com.cn
"
;
string
from
=
"
pcmax@powerise.com.cn
"
;
string
to
=
"
pcmax@etang.com
"
;
string
subject
=
"
test
"
;
string
body
=
"
hello
"
;
try
{ // MailMessage表明电子邮件 using (MailMessage message = new MailMessage(from, to, subject, body)) { //SmtpClient是发送邮件的主体,这个构造函数是告知SmtpClient发送邮件时使用哪个SMTP服务器 System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient(mailServerName); mailClient.UseDefaultCredentials = true; // 最终的发送方法 mailClient.Send(message); } Loger.Write("Message sent."); }
catch
(Exception ex)
{ Loger.Write(ex.Message); }
这个代码一般是不能被实际运用的,因为现在的邮件服务器都需要做SMTP服务器认证,哈,说了一段废话。
现在马上再介绍一段使用SMTP服务器认证来发送邮件的代码:
string
mailServerName
=
"
smtp.21cn.com
"
;
string
from
=
"
amax@21cn.com
"
;
string
to
=
"
amax@21cn.com
"
;
string
subject
=
"
test
"
;
string
body
=
"
hello
"
;
using
(MailMessage message
=
new
MailMessage(from, to, subject, body))
{ //SmtpClient是发送邮件的主体,这个构造函数是告知SmtpClient发送邮件时使用哪个SMTP服务器 System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient(mailServerName); //构建一个认证实例 System.Net.NetworkCredential nc = new System.Net.NetworkCredential("amax@21cn.com","******"); //将认证实例赋予mailClient mailClient.Credentials = nc; //千万不要再画蛇添足在“mailClient.Credentials = nc;”语句下再对mailclient.UseDefaultCredentials赋值了,不管是false还是true,都将导致程序运行出错 // 最终的发送方法 mailClient.Send(message); }
目前大家看到的都是通过Code来进行邮件发送的,而在Asp.Net2.0中Framework考虑更多的是配置式,也就是通过config方式来进行应用程序的控制,而不是把绝大多数的参数都硬编码,查阅SDK后可以看到有个mailSettings的配置节,在SDK用红色文字显注的表示了“此属性在 .NET Framework 2.0 版中是新增的” ,这个配置节属于<system.net>节下的。
接下来我们把上面的代码用一些配置信息来取得,马上会得知你的Code是多么简洁。 config:
<
mailSettings
>
<
smtp
from
="amax@21cn.com"
>
<
network
host
="mail.21cn.com"
password
="*********"
port
="25"
userName
="amax"
defaultCredentials
="false"
/>
</
smtp
>
</
mailSettings
>
code:
string
subject
=
"
test
"
;
string
body
=
"
hello
"
; SmtpSection smtpSec
=
(SmtpSection)ConfigurationManager.GetSection(
"
system.net/mailSettings/smtp
"
);
using
(MailMessage message
=
new
MailMessage(smtpSec.From,
"
amax@21cn.com
"
, subject, body))
{ System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient(); mailClient.Send(message); }