日期:2011-08-09  浏览次数:20470 次

首先,我们来介绍一下.net类库种自带的smtp类。
  在.NET中的System.Web.Mail名字空间下,有一个专门使用SMTP协议来发送邮件的类:SmtpMail,它已能满足最普通的发送邮件的需求。这个类只有一个自己的公共函数--Send()和一个公共属性—SmtpServer
您必须通过SmtpServer属性来指定发送邮件的服务器的名称(或IP地址),然后再调用
Send()函数来发送邮件。
代码示例如下:
(in C#)
using System.Web.Mail;
public void sendMail()
{
try
{
System.Web.Mail.MailMessage myMail=new MailMessage();
myMail.From = "myaccount@test.com";
myMail.To = "myaccount@test.com";
myMail.Subject = "MailTest";
myMail.Priority = MailPriority.Low;
myMail.BodyFormat = MailFormat.Text;
myMail.Body = "Test";
SmtpMail.SmtpServer="smarthost"; //your smtp server here


smtpmail.send(mymail);
}
catch(Exception e)
{
throw e;
}
}
您可以在Send函数的参数MailMessage对象中设置邮件的相关属性,如优先级、附件等等。除了以MailMessage对象为参数(如上述代码),Send函数还可以简单的直接以邮件的4个主要信息(from,to,subject,messageText)作为字符串参数来调用。


第二、使用cdo组件发送邮件
  CDO是Collaboration Data Objects的简称,它是一组高层的COM对象集合,并经历了好几个版本的演化,现在在Windows2000和Exchange2000中使用的都是CDO2.0的版本(分别为cdosys.dll和cdoex.dll)。CDOSYS构建在SMTP协议和NNTP协议之上,并且作为Windows2000 Server的组件被安装,您可以在系统目录(如c:\winnt或c:\windows)的system32子目录中找到它(cdosys.dll)。
  CDO组件相对于先前介绍的SmtpMail对象功能更为丰富,并提供了一些SmtpMail类所没有提供的功能,如通过需要认证的SMTP服务器发送邮件等。
下面一段代码就展示了如何使用CDO组件通过需要认证的SMTP服务器发送邮件的过程:
(in C#)
public void CDOsendMail()
{
try
{
CDO.Message oMsg = new CDO.Message();

oMsg.From = "myaccount@test.com";
oMsg.To = "myaccount@test.com";
oMsg.Subject = "MailTest";

oMsg.HTMLBody = "Test";


cdo.iconfiguration iConfg = oMsg.Configuration;
ADODB.Fields oFields = iConfg.Fields;

oFields["http://schemas.microsoft.com/cdo/configuration/sendusing"].Value=2;
oFields["http://schemas.microsoft.com/cdo/configuration/sendemailaddress"].Value="myaccount@test.com"; //sender mail
oFields["http://schemas.microsoft.com/cdo/configuration/smtpaccountname"].Value="myaccount@test.com"; //email account
oFields["http://schemas.microsoft.com/cdo/configuration/sendusername"].Value="username";
oFields["http://schemas.microsoft.com/cdo/configuration/sendpassword"].Value="password";
oFields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"].Value=1;
//value=0 代表Anonymous验证方式(不需要验证)
//value=1 代表Basic验证方式(使用basic (clear-text) authentication.
//The configuration sendusername/sendpassword or postusername/postpassword fields are used to specify credentials.)
//Value=2 代表NTLM验证方式(Secure Password Authentication in Microsoft Outlook Express)
oFields["http://schemas.microsoft.com/cdo/configuration/languagecode"].Value=0x0804;
oFields["http://schemas.microsoft.com/cdo/configuration/smtpserver"].Value="smtp.21cn.com";


ofields.update();
oMsg.BodyPart.Charset="gb2312";
oMsg.HTMLBodyPart.Charset="gb2312";


omsg.send();
oMsg = null;
}
catch (Exception e)
{
throw e;
}
}
注意:由于Exchange2000的CDO组件cdoex.dll会更新原有的Windows2000的CDO组件cdosys.dll,所以如果您希望继续使用cdosys.dll,您必须先通过regsrv32.exe卸载掉cd