在C#中如何通过需要用户认证的SMTP服务器发送Email

在c#中,我们一般可以使用System.Web.Mail下的MailMessage来发送Email:

using System.Web.Mail;

public void SendMail()

{

MailMessage Msg = new MailMessage();

Msg.To = " [email protected] ";

Msg.Subject = "hello";

Msg.Body = "Testing Email";

Msg.From=" [email protected] ";

SmtpMail.SmtpServer="smtp.netease.com"; //<<===注意这个地址

SmtpMail.Send(Msg);

return;

}

但事实上上面的代码无法正常工作,原因在于smtp.netease.com要求用户认证,而一开始我发现SmtpMail只能使用允许匿名用户的smtp服务器(想想现在还有支持匿名访问的smtp服务器吗?都是该死的垃圾邮件害的 :-) )。我查了一下资料,发现在c#中我们仍然需要通过调用COM(CDO for Windows 2000)来完成用户认证的功能。

下面是测试代码, 测试通过:VS.NET+Win2k Prof.

//在reference中添加CDO for Windows 2000

using CDO;

public void SendEmail()
{

try
{
Configuration conf=new ConfigurationClass();

conf.Fields[CdoConfiguration.cdoSendUsingMethod].Value=CdoSendUsing.cdoSendUsingPort;
conf.Fields[CdoConfiguration.cdoSMTPServer].Value="smtp.netease.com";
conf.Fields[CdoConfiguration.cdoSMTPServerPort].Value=25;
conf.Fields[CdoConfiguration.cdoSMTPAccountName].Value="hydnoahark";
conf.Fields[CdoConfiguration.cdoSendUserReplyEmailAddress].Value=""hydnoahark" < [email protected] >";
conf.Fields[CdoConfiguration.cdoSendEmailAddress].Value=""hydnoahark" < [email protected] >";
conf.Fields[CdoConfiguration.cdoSMTPAuthenticate].Value=CdoProtocolsAuthentication.cdoBasic;
conf.Fields[CdoConfiguration.cdoSendUserName].Value="hydnoahark";
conf.Fields[CdoConfiguration.cdoSendPassword].Value="xxx";

conf.Fields.Update();

MessageClass msg=new MessageClass();
msg.Configuration=conf;

msg.To=" [email protected] ";
msg.Subject="Hello";
msg.TextBody="It's test";
msg.From=" [email protected] ";

msg.Send();
}
catch(System.Runtime.InteropServices.COMException e)
{
MessageBox.Show(e.ToString());
}

return;
}

OK, 就是这么简单,不知道其他人有没更好的方法,可以的话给我一个建议 ^_^

Published At
Categories with Web编程
Tagged with
comments powered by Disqus