在asp中,就可以通过调用cdonts组件发送简单邮件,在asp.net中,自然也可以。不同的是,.net framework中,将这一组件封装到了system.web.mail命名空间中。
一个典型的邮件发送程序如下:
<%@ import namespace="system.web.mail" %>
<script runat="server">
mailmessage mail=new mailmessage();
mail.from="service@brookes.com";
mail.to="brookes@brookes..com";
mail.bodyformat=mailformat.text;
mail.body="a test smtp mail.";
mail.subject="r u ok?";
smtpmail.smtpserver="localhost";
smtpmail.send(mail);
</script>
通常情况下,系统调用iis自带的默认smtp虚拟服务器就可以实现邮件的发送。但是也经常会遇到这样的错误提示:
the server rejected one or more recipient addresses. the server response was: 550 5.7.1 unable to relay for brookes@brookes.com
产生这个错误的原因除了地址错误的可能外,还有一个重要原因。如上文提到的,iis并不带有真正的邮件功能,只是借用一个“smtp虚拟服务器”实现邮件的转发。在msdn中,有如下提示:
如果本地 smtp 服务器(包括在 windows 2000 和 windows server 2003 中)位于阻塞任何直接 smtp 通信量(通过端口 25)的防火墙之后,则需要查找网络上是否有可用的智能主机能用来中转发往 internet 的 smtp 消息。
智能主机是一个 smtp 服务器,它能够中转从内部 smtp 服务器直接发送到 internet 的外出电子邮件。智能主机应能同时连接到内部网络和 internet,以用作电子邮件网关。
打开默认smtp虚拟服务器-属性-访问-中继限制,可以看到,这种转发或者中继功能受到了限制。在限制列表中,添加需要使用此服务器的主机的ip地址,就可以解决上文提到的问题。
如果不使用iis自带的smtp虚拟服务器而使用其他真正的邮件服务器,如imail,exchange等,常常遇到服务器需要寄送者身份验证的问题(esmtp)。在使用需要验证寄送者身份的服务器时,会出现错误:
the server rejected one or more recipient addresses. the server response was: 550 not local host ckocoo.com, not a gateway
以前在asp中,遇到这种问题没有什么解决的可能,只能直接使用cdo组件(cdonts的父级组件):
conf.fields[cdoconfiguration.cdosmtpauthenticate].value=cdoprotocolsauthentication.cdobasic;
conf.fields[cdoconfiguration.cdosendusername].value="brookes";
conf.fields[cdoconfiguration.cdosendpassword].value="xxxxxxx";
在.net framework 1.1中,显然对这一需求有了考虑,在mailmessage组件中增加了fields集合易增加esmtp邮件服务器中的寄送者身份验证的问题。不过,这一方法仅适用于.net framework 1.1,不适用于.net framework 1.0版本。带有寄送者身份验证的邮件发送程序如下:
<%@ import namespace="system.web.mail" %>
<script runat="server">
mailmessage mail=new mailmessage();
mail.from="service@brookes.com";
mail.to="brookes@brookes.com";
mail.bodyformat=mailformat.text;
mail.body="a test smtp mail.";
mail.subject="r u ok?";
mail.fields.add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //basic authentication
mail.fields.add("http://schemas.microsoft.com/cdo/configuration/sendusername", "brookes"); //set your username here
mail.fields.add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "walkor"); //set your password here
smtpmail.smtpserver="lsg.moon.net";
smtpmail.send(mail);
</script>
有了这种方法,终于可以不必再借助于jmail、easymail等第三方组件,而只简单使用smtpmai就可以l完成邮件的发送了!
参考:how do i authenticate to send an email?
