日期:2014-05-19  浏览次数:20371 次

请教一个关于邮件发送的问题
我的代码里的发送邮件的方法是这样的
public   static   void   CDOsendmail(string   from,string   to,string   subject,string   body,string   userName,string   userPwd,string   smtpServer)
{
MailMessage   msg   =   new   MailMessage();
msg.From   =from;
msg.To   =   to;
msg.Subject   =   subject;
msg.Body   =   body;
msg.Fields.Add( "http://schemas.microsoft.com/cdo/configuration/smtpauthenticate ",1);
msg.Fields.Add( "http://schemas.microsoft.com/cdo/configuration/sendusername ",userName);
msg.Fields.Add( "http://schemas.microsoft.com/cdo/configuration/sendpassword ",userPwd);
SmtpMail.SmtpServer   =   smtpServer;
SmtpMail.Send(msg);
msg   =   null;
}


然后我的web.config中存了必要的一些数据,部分如下:
    <appSettings>
<add   key   =   "strcon "   value   =   "server   =   .;database   =   eshop;uid   =   sa;pwd   = "   />
<add   key= "mailFrom "   value= "我的163登陆帐号 "> </add>
<add   key= "userName "   value= "hahaha@163.com "> </add>
<add   key= "password "   value= "我的密码 "> </add>
<add   key= "mailSubject "   value= "成功找回您的密码 "> </add>
<add   key= "mailSmtp "   value= "smtp.163.com "> </add>
    </appSettings>    

这写代码至少在拼写上我都保证没有错,这些web.config中的值是会经过一个方法传给上面的CDOsendmail()方法的,但是在执行到CDOsendmail()方法中的 SmtpMail.Send(msg);时,就会抛出异常,请大哥们帮我检查看一下是怎么回事。我老是怀疑是不是163现在的smtpServer不是smtp.163.com

------解决方案--------------------
很简单就这么几句
步骤1:using System.Net.Mail;

步骤2: #region 电子邮件发送新密码给用户
private void SendEmail()
{
try
{
MailMessage m_message = new MailMessage();

m_message.From = new MailAddress( "admin@xunku.cn ");

m_message.To.Add(new MailAddress( "hzl091@126.com "));

m_message.Subject = "hello ";

m_message.Body = "正在进行邮件发送测试, <font color= 'red '> <a href= 'http://www.xunku.cn '> 去讯酷看看 </a> </font> ";

SmtpClient m_smtpClient = new SmtpClient();

m_smtpClient.Send(m_message);

}
catch (Exception ex)
{
throw ex;
}
}
#endregion 电子邮件发送新密码给用户

步骤3:配置web.config(可以利用网站管理工具来配置)
<system.net>
<mailSettings>
<smtp from= "admin@xunku.cn ">
<network host= "mail.xunku.cn " password= "******** " userName= "admin@xunku.cn " />
</smtp>
</mailSettings>
</system.net>

注意:特别要说明的是有些免费邮箱是不支持SMTP协议的,所以如果你用下面的配置发送邮件将会失败
<system.net>
<mailSettings>
<smtp from= "hzl091@163.com ">
<network host= "mail.163.com " password= "******** " userName= "hzl091@163.com " />
</smtp>
</mailSettings>
</system.net>