您的位置:首页 > 编程语言 > ASP

VS2005(asp.net2.0)轻松发送邮件。

2008-03-06 16:10 344 查看
VS2005(asp.net2.0)轻松发送邮件。

在asp.net 2.0里面可以很简单地开发出来smtp发送电子邮件。不像asp还得注册jmail控件什么的。

需要引用下列命名空间:
using System.Net.Mail;
using System.Net;

下面是通过smtp.126.com发送邮件。smtp.126.com需要身份验证。
protected void SendMail_Click(object sender, EventArgs e)
{
string to = "xpnew@126.com";
string from = "xpnew@126.com";
string subject = MailTitle.Text;// "Using the new SMTP client.";
string body = MailBody.Text;// @"Using this new feature, you can send an e-mail message from an application very easily.";
MailMessage message = new MailMessage(from, to, subject, body);
SmtpClient client = new SmtpClient("smtp.126.com", 25);
// Credentials are necessary if the server requires the client
// to authenticate before it will send e-mail on the client's behalf.
//client.Credentials = CredentialCache.DefaultNetworkCredentials;
client.Credentials = new NetworkCredential("xpnew", "XXXXXX");//这里是改成你自己的账号和密码
client.Send(message);
}

下面是通过本机(IIS自带的smtp服务器)发送,没有身份验证。
这个其实也很有用,通常来说,实际工作当中会遇到开发企业内部的web应用程序(比如说OA),那么就得使用内部的smtp服务器了。
只可惜,搞了一下午也没有通过测试。(不能中继到internet)
protected void SendFromLocal_Click(object sender, EventArgs e)
{
string to = "xpnew@126.com";
string from = "xpnew@126.com";
string subject = MailTitle.Text;// "Using the new SMTP client.";
string body = MailBody.Text;// @"Using this new feature, you can send an e-mail message from an application very easily.";
MailMessage message = new MailMessage(from, to, subject, body);
SmtpClient client = new SmtpClient("localhost", 25);

// Credentials are necessary if the server requires the client
// to authenticate before it will send e-mail on the client's behalf.
client.Credentials = CredentialCache.DefaultNetworkCredentials;
client.Send(message);
}

通过本机发送的时候,可能会出现一些问题。
1、"邮箱不可用。 服务器响应为: 5.7.1 Unable to relay for xpnew@126.com"
解决办法:
在IIS中,右击“默认SMTP虚拟服务器”,选择“属性”,切换到“访问”页,点击“中继”按钮,在弹出框中选择“仅以下列表除外”,确定。
2、邮件发送出去了,但是对方却收不到。
原因暂时还没有找到。在网上查找了一些资料,好像是因为被对方的服务器认定为垃圾邮件了。

参考资料:

1、MSDN:.NET Framework 类库 SmtpClient.Credentials 属性

2、vs2003 和vs2005下的发送SMTP邮件 (downmoon原创)
http://dev.21tx.com/2006/01/22/10217.html

3、出错:5.7.1

http://blog.csdn.net/beimuaihui/archive/2007/08/12/1739409.aspx

4、在Win2003中为 Internet 信息服务 SMTP 邮件中继服务器配置远程域
http://www.knowsky.com/341533.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: