三种使用SMTP协议发送邮件的方法

本文介绍了在C#中实现邮件发送的三种方式。一是使用.NET类库自带的SMTP类SmtpMail,通过指定服务器名称或IP地址调用Send函数发送;二是使用CDO组件,功能更丰富,可通过认证服务器发送;三是使用Socket撰写发送程序,还介绍了带验证的SMTP服务器身份验证过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一、.NET类库种自带的SMTP类:SmtpMail

  在.NET中的System.Web.Mail名字空间下,有一个专门使用SMTP协议来发送邮件的类:SmtpMail,它已能满足最普通的发送邮件的需求。这个类只有一个自己的公共函数--Send()和一个公共属性—SmtpServer,您必须通过SmtpServer属性来指定发送邮件的服务器的名称(或IP地址),然后再调用Send()函数来发送邮件。 
   代码示例如下: 

 1 None.gif using  System.Web.Mail; 
 2 None.gif public   void  sendMail() 
 3 ExpandedBlockStart.gifContractedBlock.gif dot.gif
 4InBlock.giftry 
 5ExpandedSubBlockStart.gifContractedSubBlock.gifdot.gif
 6InBlock.gifSystem.Web.Mail.MailMessage myMail=new MailMessage(); 
 7InBlock.gifmyMail.From = "myaccount@test.com"
 8InBlock.gifmyMail.To = "myaccount@test.com"
 9InBlock.gifmyMail.Subject = "MailTest"
10InBlock.gifmyMail.Priority = MailPriority.Low; 
11InBlock.gifmyMail.BodyFormat = MailFormat.Text; 
12InBlock.gifmyMail.Body = "Test"
13InBlock.gifSmtpMail.SmtpServer="smarthost"//your smtp server here 
14InBlock.gif
15InBlock.gif SmtpMail.Send(myMail); 
16ExpandedSubBlockEnd.gif}
 
17InBlock.gifcatch(Exception e) 
18ExpandedSubBlockStart.gifContractedSubBlock.gifdot.gif
19InBlock.gifthrow e; 
20ExpandedSubBlockEnd.gif}
 
21ExpandedBlockEnd.gif}

22 None.gif

 
  您可以在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服务器发送邮件的过程:

 1 None.gif public   void  CDOsendMail() 
 2 ExpandedBlockStart.gifContractedBlock.gif dot.gif
 3InBlock.giftry 
 4ExpandedSubBlockStart.gifContractedSubBlock.gifdot.gif
 5InBlock.gifCDO.Message oMsg = new CDO.Message(); 
 6InBlock.gif
 7InBlock.gifoMsg.From = "myaccount@test.com"
 8InBlock.gifoMsg.To = "myaccount@test.com"
 9InBlock.gifoMsg.Subject = "MailTest"
10InBlock.gifoMsg.HTMLBody = "Test"
11InBlock.gif
12InBlock.gifCDO.IConfiguration iConfg = oMsg.Configuration; 
13InBlock.gifADODB.Fields oFields = iConfg.Fields; 
14InBlock.gif
15InBlock.gifoFields["http://schemas.microsoft.com/cdo/configuration/sendusing"].Value=2
16InBlock.gifoFields["http://schemas.microsoft.com/cdo/configuration/sendemailaddress"].Value = "myaccount@test.com"//sender mail 
17InBlock.gifoFields["http://schemas.microsoft.com/cdo/configuration/smtpaccountname"].Value = "myaccount@test.com"//email account 
18InBlock.gifoFields["http://schemas.microsoft.com/cdo/configuration/sendusername"].Value="username"
19InBlock.gifoFields["http://schemas.microsoft.com/cdo/configuration/sendpassword"].Value="password"
20InBlock.gifoFields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"].Value=1
21InBlock.gif//value=0 代表Anonymous验证方式(不需要验证) 
22InBlock.gif//value=1 代表Basic验证方式(使用basic (clear-text) authentication. 
23InBlock.gif//The configuration sendusername/sendpassword or postusername/postpassword fields are used to specify credentials.) 
24InBlock.gif//Value=2 代表NTLM验证方式(Secure Password Authentication in Microsoft Outlook Express) 
25InBlock.gifoFields["http://schemas.microsoft.com/cdo/configuration/languagecode"].Value=0x0804
26InBlock.gifoFields["http://schemas.microsoft.com/cdo/configuration/smtpserver"].Value="smtp.21cn.com"
27InBlock.gifoFields.Update(); 
28InBlock.gifoMsg.BodyPart.Charset="gb2312"
29InBlock.gifoMsg.HTMLBodyPart.Charset="gb2312"
30InBlock.gif
31InBlock.gifoMsg.Send(); 
32InBlock.gifoMsg = null
33ExpandedSubBlockEnd.gif}
 
34InBlock.gifcatch (Exception e) 
35ExpandedSubBlockStart.gifContractedSubBlock.gifdot.gif
36InBlock.gifthrow e; 
37ExpandedSubBlockEnd.gif}
 
38ExpandedBlockEnd.gif}

39 None.gif
40 None.gif


  注意:由于Exchange2000的CDO组件cdoex.dll会更新原有的Windows2000的CDO组件cdosys.dll,所以如果您希望继续使用cdosys.dll,您必须先通过regsrv32.exe卸载掉cdoex.dll。

第三、使用Socket撰写邮件发送程序

  当然,如果您觉得SmtpMail不能满足您的需求,CDO又不够直截了当,那就只能自己动手了;其实如果您很熟悉Socket编程,自己写一个发送邮件的程序并不很难,以下就是一个例子。
首先,我们简单介绍一下带验证的SMTP服务器如何使用AUTH原语进行身份验证,其详细的定义可以参考RFC2554。

  具体如下:

  1)首先,需要使用EHLO而不是原先的HELO。

  2)EHLO成功以后,客户端需要发送AUTH原语,与服务器就认证时用户名和密码的传递方式进行协商。

  3)如果协商成功,服务器会返回以3开头的结果码,这是就可以把用户名和密码传给服务器。

  4)最后,如果验证成功,就可以开始发信了。

  下面是一个实际的例子,客户端在WinXP的Command窗口中通过"telnet smtp.263.NET 25"命令连接到263的smtp服务器发信:

220 Welcome to coremail System(With Anti-Spam) 2.1
EHLO 263.NET
250-192.168.30.29
250-PIPELINING
250-SIZE 10240000
250-ETRN
250-AUTH LOGIN
250 8BITMIME
AUTH LOGIN
334 VXNlcm5hbWU6
bXlhY2NvdW50
334 UGFzc3dvcmQ6
bXlwYXNzd29yZA==
235 Authentication successful
MAIL FROM:myaccount@263.NET
250 Ok
RCPT TO:myaccount@263.NET
250 Ok
Data
354 End data with .
This is a testing email.
haha.
.
250 Ok: queued as AC5291D6406C4
QUIT
221 Bye

  上面的内容就是发信的全过程。其中与身份验证有关的主要是第九到第十四行:

AUTH LOGIN "客户端输入
334 VXNlcm5hbWU6 "服务器提示“Username:="
bXlhY2NvdW50 "客户端输入“myaccount="的Base64编码
334 UGFzc3dvcmQ6 "服务器提示“Password:="
bXlwYXNzd29yZA== "客户端输入“mypassword="的Base64编码
235 Authentication successful "服务器端通过验证

  从上面的分析可以看出,在这个身份验证过程中,服务器和客户端都直接通过Socket传递经过标准Base64编码的纯文本。这个过程可以非常方便的用C#实现,或者直接添加到原有的源代码中。

  另外,有些ESMTP服务器不支持AUTH LOGIN方式的认证,只支持AUTH CRAM-MD5方式验证。但是这两者之间的区别只是文本的编码方式不同。

  实现此功能的源代码可以在SourceForge.NET http://sourceforge.NET/projects/opensmtp-net/ 上找到下载。下面给出了一个简单的伪码:

 1 None.gif public   void  SendMail(MailMessage msg) 
 2 ExpandedBlockStart.gifContractedBlock.gif dot.gif
 3InBlock.gifNetworkStream nwstream = GetConnection(); 
 4InBlock.gif
 5InBlock.gifWriteToStream(ref nwstream, "EHLO " + smtpHost + "\r\n"); 
 6InBlock.gifstring welcomeMsg = ReadFromStream(ref nwstream); 
 7InBlock.gif
 8InBlock.gif// implement HELO command if EHLO is unrecognized. 
 9InBlock.gifif (IsUnknownCommand(welcomeMsg)) 
10ExpandedSubBlockStart.gifContractedSubBlock.gifdot.gif
11InBlock.gifWriteToStream(ref nwstream, "HELO " + smtpHost + "\r\n"); 
12ExpandedSubBlockEnd.gif}
 
13InBlock.gifCheckForError(welcomeMsg, ReplyConstants.OK); 
14InBlock.gif
15InBlock.gif// Authentication is used if the u/p are supplied 
16InBlock.gifAuthLogin(ref nwstream); 
17InBlock.gif
18InBlock.gifWriteToStream(ref nwstream, "MAIL FROM: <" + msg.From.Address + ">\r\n"); 
19InBlock.gifCheckForError(ReadFromStream(ref nwstream), ReplyConstants.OK); 
20InBlock.gif
21InBlock.gifSendRecipientList(ref nwstream, msg.To); 
22InBlock.gifSendRecipientList(ref nwstream, msg.CC); 
23InBlock.gifSendRecipientList(ref nwstream, msg.BCC); 
24InBlock.gif
25InBlock.gifWriteToStream(ref nwstream, "DATA\r\n"); 
26InBlock.gifCheckForError(ReadFromStream(ref nwstream), ReplyConstants.START_INPUT); 
27InBlock.gif
28InBlock.gifif (msg.ReplyTo.Name != null && msg.ReplyTo.Name.Length != 0
29ExpandedSubBlockStart.gifContractedSubBlock.gifdot.gif{ WriteToStream(ref nwstream, "Reply-To: \"" + msg.ReplyTo.Name + "\" <" + 
30ExpandedSubBlockEnd.gifmsg.ReplyTo.Address + ">\r\n"); }
 
31InBlock.gifelse 
32ExpandedSubBlockStart.gifContractedSubBlock.gifdot.gif{ WriteToStream(ref nwstream, "Reply-To: <" + msg.ReplyTo.Address + ">\r\n"); } 
33InBlock.gif
34InBlock.gifif (msg.From.Name != null && msg.From.Name.Length != 0
35ExpandedSubBlockStart.gifContractedSubBlock.gifdot.gif{ WriteToStream(ref nwstream, "From: \"" + msg.From.Name + "\" <" + 
36ExpandedSubBlockEnd.gifmsg.From.Address + ">\r\n"); }
 
37InBlock.gifelse 
38ExpandedSubBlockStart.gifContractedSubBlock.gifdot.gif{ WriteToStream(ref nwstream, "From: <" + msg.From.Address + ">\r\n"); } 
39InBlock.gif
40InBlock.gifWriteToStream(ref nwstream, "To: " + CreateAddressList(msg.To) + "\r\n"); 
41InBlock.gif
42InBlock.gifif (msg.CC.Count != 0
43ExpandedSubBlockStart.gifContractedSubBlock.gifdot.gif{ WriteToStream(ref nwstream, "CC: " + CreateAddressList(msg.CC) + "\r\n"); } 
44InBlock.gif
45InBlock.gifWriteToStream(ref nwstream, "Subject: " + msg.Subject + "\r\n"); 
46InBlock.gif
47InBlock.gifif (msg.Priority != null
48ExpandedSubBlockStart.gifContractedSubBlock.gifdot.gif{ WriteToStream(ref nwstream, "X-Priority: " + msg.Priority + "\r\n"); } 
49InBlock.gif
50InBlock.gifif (msg.Headers.Count > 0
51ExpandedSubBlockStart.gifContractedSubBlock.gifdot.gif
52InBlock.gifSendHeaders(ref nwstream, msg); 
53ExpandedSubBlockEnd.gif}
 
54InBlock.gif
55InBlock.gifif (msg.Attachments.Count > 0 ¦ ¦ msg.HtmlBody != null
56ExpandedSubBlockStart.gifContractedSubBlock.gifdot.gif
57InBlock.gifSendMessageBody(ref nwstream, msg); 
58ExpandedSubBlockEnd.gif}
 
59InBlock.gifelse 
60ExpandedSubBlockStart.gifContractedSubBlock.gifdot.gif
61InBlock.gifWriteToStream(ref nwstream, msg.Body + "\r\n"); 
62ExpandedSubBlockEnd.gif}
 
63InBlock.gif
64InBlock.gifWriteToStream(ref nwstream, "\r\n.\r\n"); 
65InBlock.gifCheckForError(ReadFromStream(ref nwstream), ReplyConstants.OK); 
66InBlock.gifWriteToStream(ref nwstream, "QUIT\r\n"); 
67InBlock.gifCheckForError(ReadFromStream(ref nwstream), ReplyConstants.QUIT); 
68InBlock.gifCloseConnection(); 
69ExpandedBlockEnd.gif}


 

转载于:https://www.cnblogs.com/net66/archive/2005/07/25/199956.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值