在.net中使用CDO发送邮件(已调试通过)

第一步:   先配置web.config文件,如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
     <!--数据库连接字符串-->
    <add key="P_Con" value="server=(local);database=pub;UID=sa;Password=;"></add>
    <!--smtp验证所需用户名-->
    <add key="mailUser" value="你的邮箱用户名"></add>
    <!--smtp验证所需密码-->
    <add key="mailPwd" value="你的邮箱密码"></add>
    <!--smtp服务器-->
    <add key="mailSmtpServer" value="smtp.163.com"></add>
     <!--发信人地址,必须为正确格式的Email地址-->
     <add key="mailSender" value="###@163.com"></add>
     <!--发信的主题-->
     <add key="mailTitle" value="邮件标题"></add>
    </appSettings>
第二步: 添加CDO引用(需要到相关网站下载CDO.dll文件)以及ADODB(.net自带)引用

第三步: 写Mail.cs类文件,代码如下:

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace Mail.BLL
{
 /// <summary>
 /// Mail 的摘要说明。
 /// </summary>
 public class Mail
 {
  public Mail()
  {
  
  }

  public static void CDOsendmail(string from, string to, string subject,
   string body, string userName, string password, string smtpServer)
  {
   //声明新的邮件实例
   CDO.Message Msg = new CDO.Message();
   //分别设置发送人、收信人、主题、内容
   Msg.From = from;
   Msg.To = to;
   Msg.Subject = subject;
   Msg.HTMLBody = "<html><body>"+body
    +"</body></html>";
   //设置发送参数,包括smtpServer,用户名,密码
   CDO.IConfiguration Config = Msg.Configuration;
   ADODB.Fields oFields = Config.Fields;
   oFields["http://schemas.microsoft.com/cdo/configuration/sendusing"].Value = 2;
   oFields["http://schemas.microsoft.com/cdo/configuration/sendusername"].Value=userName;
   oFields["http://schemas.microsoft.com/cdo/configuration/sendpassword"].Value=password;
   oFields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"].Value=1;
   oFields["http://schemas.microsoft.com/cdo/configuration/languagecode"].Value=0x0804;
   oFields["http://schemas.microsoft.com/cdo/configuration/smtpserver"].Value=smtpServer;
   oFields.Update();
   //字符格式
   Msg.BodyPart.Charset = "gb2312";
   Msg.HTMLBodyPart.Charset = "gb2312";
   //发送
   Msg.Send();
   Msg = null; 
  }
 }
}

第四步:在相关页面中添加发送邮件事件

如下是一个.aspx文件,找回的密码会被发送到用户的邮箱里面:(Getbakckpassword.aspx)

<%@ Page language="c#" Codebehind="GetBackPassword.aspx.cs" AutoEventWireup="false" Inherits="job_17.GetBackPassword" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
 <HEAD>
  <title>GetBackPassword</title>
  <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
  <meta name="CODE_LANGUAGE" Content="C#">
  <meta name="vs_defaultClientScript" content="JavaScript">
  <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
 </HEAD>
 <body MS_POSITIONING="GridLayout">
  <form id="Form1" method="post" runat="server">
   <FONT face="宋体">
    <TABLE id="Table2" style="Z-INDEX: 101; LEFT: 8px; POSITION: absolute; TOP: 8px" cellSpacing="0"
     cellPadding="0" width="100%" border="0">
     <TBODY>
      <TR>
       <TD colSpan="2"></TD>
      </TR>
      <TR>
       <TD vAlign="top" width="145"><IMG height="1" src="images/space.gif" width="145">
       </TD>
       <TD vAlign="top" align="left" width="700">
        <TABLE id="Table4" width="100%" align="left" border="0">
         <TBODY>
          <TR vAlign="top">
           <TD align="left">
            <TABLE id="Table5" width="100%" align="center" border="0">
             <TBODY>
              <TR vAlign="midddle">
               <TD align="center">
                <TABLE id="Table1" cellSpacing="0" cellPadding="0" width="100%" align="center" border="0">
                 <TBODY>
                  <TR>
                   <TD vAlign="middle" align="center">
                    <DIV id="Div1" width="80%">
                     <DIV id="PanelEx1" style="BORDER-RIGHT: #ffcc66 2px solid; BORDER-TOP: #ffcc66 2px solid; BORDER-LEFT: #ffcc66 2px solid; WIDTH: 320px; BORDER-BOTTOM: #ffcc66 2px solid; HEIGHT: 120px">
                      <TABLE id="TitleTable001" style="Z-INDEX: 102; WIDTH: 316px; HEIGHT: 17px" cellSpacing="1"
                       cellPadding="1" width="316" bgColor="#ffcc66" border="0">
                       <TR>
                        <TD align="center" colSpan="3"><SPAN style="FONT-SIZE: x-small; COLOR: white"><FONT face="宋体" size="4"><B>找回密码</B></FONT></SPAN></TD>
                       </TR>
                      </TABLE>
                      <SPAN id="PanelEx1_Label1">
                       <TABLE id="table3" width="70%" align="center">
                        <TBODY align="right">
                         <TR>
                          <TD align="center">
                           <asp:Label id="Message" Runat="server" BorderColor="red" ForeColor="Red"></asp:Label></TD>
                         </TR>
                         <TR>
                          <TD><FONT size="+0">用户名:</FONT>
                           <asp:TextBox id="LoginName" Runat="server" BorderStyle="Groove" Width="136px"></asp:TextBox>
                          </TD>
                         </TR>
                         <TR>
                          <TD align="center">
                           <asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ControlToValidate="LoginName" ErrorMessage="请输入用户名"
                            Display="Dynamic"></asp:RequiredFieldValidator></TD>
                         </TR>
                         <TR>
                          <TD noWrap><FONT size="+0">密码提示问题:</FONT>
                           <asp:TextBox id="Question" Runat="server" BorderStyle="Groove" Width="136px"></asp:TextBox>
                          </TD>
                         </TR>
                         <TR>
                          <TD noWrap>
                           <asp:RequiredFieldValidator id="RequiredFieldValidator4" runat="server" ControlToValidate="Question" ErrorMessage="请输入密码提示问题"
                            Display="Dynamic"></asp:RequiredFieldValidator></TD>
                         </TR>
                         <TR>
                          <TD noWrap><FONT size="+0">提示问题答案:</FONT>
                           <asp:TextBox id="Answer" Runat="server" BorderStyle="Groove" Width="136px"></asp:TextBox>
                          </TD>
                         </TR>
                         <TR>
                          <TD noWrap><FONT face="宋体">
                            <asp:RequiredFieldValidator id="RequiredFieldValidator5" runat="server" ControlToValidate="Answer" ErrorMessage="请输入密码提示问题答案"
                             Display="Dynamic"></asp:RequiredFieldValidator></FONT></TD>
                         </TR>
                         <TR>
                          <TD noWrap><FONT size="+0">Email:</FONT>
                           <asp:TextBox id="Email" Runat="server" BorderStyle="Groove" Width="136px"></asp:TextBox>
                          </TD>
                         </TR>
                         <TR>
                          <TD noWrap><FONT face="宋体">
                            <asp:RequiredFieldValidator id="RequiredFieldValidator2" runat="server" ControlToValidate="Email" ErrorMessage="Email不能为空"
                             Display="Dynamic"></asp:RequiredFieldValidator>
                            <asp:RegularExpressionValidator id="ValidateEmail" runat="server" ControlToValidate="Email" ErrorMessage="Email格式不正确"
                             Display="Dynamic" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator></FONT></TD>
                         </TR>
                         <TR align="center">
                          <TD align="center">
                           <asp:Button id="Submit" Runat="server" Width="56px" Text="提交" style="BORDER-RIGHT:#000000 1px solid; BORDER-TOP:#000000 1px solid; BORDER-LEFT:#000000 1px solid; BORDER-BOTTOM:#000000 1px solid"></asp:Button>&nbsp;
                           &nbsp; <INPUT id="btn" style="BORDER-RIGHT:#000000 1px solid; BORDER-TOP:#000000 1px solid; BORDER-LEFT:#000000 1px solid; WIDTH:58px; BORDER-BOTTOM:#000000 1px solid; HEIGHT:24px"
                            type="button" value="返回" Width="56px" onclick="javascript:history.go(-1);"></TD>
                         </TR>
                        </TBODY>
                       </TABLE>
                      </SPAN>
                     </DIV>
                    </DIV>
                   </TD>
                  </TR>
                  <TR>
                   <TD vAlign="middle" align="center"></TD>
                  </TR>
                 </TBODY>
                </TABLE>
               </TD>
              </TR>
             </TBODY>
            </TABLE>
           </TD>
          </TR>
         </TBODY>
        </TABLE>
       </TD>
      </TR>
     </TBODY>
    </TABLE>
  </form>
  </FONT>
 </body>
</HTML>

其cs代码如下:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Mail.BLL;

namespace Mail
{
 /// <summary>
 /// GetBackPassword 的摘要说明。
 /// </summary>
 public class GetBackPassword : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.Button Submit;
  protected System.Web.UI.WebControls.RegularExpressionValidator ValidateEmail;
  protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator2;
  protected System.Web.UI.WebControls.TextBox Email;
  protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator5;
  protected System.Web.UI.WebControls.TextBox Answer;
  protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator4;
  protected System.Web.UI.WebControls.TextBox Question;
  protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator1;
  protected System.Web.UI.WebControls.TextBox LoginName;
  protected System.Web.UI.WebControls.Label Message;
  protected System.Web.UI.WebControls.Button btnback;
  protected System.Web.UI.HtmlControls.HtmlForm Form1;
 
  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
  }

  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
 
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {  
   this.Submit.Click += new System.EventHandler(this.Submit_Click);
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion

  private void Submit_Click(object sender, System.EventArgs e)
  {
  User user=new User();
   int result  = user.GetBackPassword(LoginName.Text.Trim(), Question.Text.Trim(),
    Answer.Text.Trim(), Email.Text);//找回密码函数
   //string sql="update person set password="
   if (result == 1)
   {
    Message.Text = "您的密码已发送,请到邮箱查收";
    //user.ChangePassword(
   }
   else
   {
    Message.Text = "您的输入信息有误!";
   }
 
  }

 

  private void btnback_Click(object sender, System.EventArgs e)
  {
  Response.Write("<script>history.go(-1);</script>");
  }
 }
}

其中有一个user封装类,代码如下:

using System;
using System.Data;
//using System.Data.SqlClient;
//using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using Mail.BLL;
using System.Web;
namespace Mail_Bll


{


 public class UserInfo
 {

  public string userRealName;
  public string zipcode;
  public string email;
  public string sex;
  public string address;
 }
 /// <summary>
 /// User 的摘要说明。
 /// </summary>
 public class User
 {
  private readonly string P_Con=ConfigurationSettings.AppSettings["P_Con"].ToString();
  public User()
  {  
  }
//  public int SignIn(string userName, string userPwd)
//  {
//   SqlParameter[] signInPara = {
//             new SqlParameter("@userName", userName),
//             new SqlParameter("@userPwd", userPwd)
//            };
//   返回userId的值,如果不存在记录,返回为0
//   return Convert.ToInt32(DAL.SQLHelper.ExecuteScalar(DAL.SQLHelper.CONN_STRING,
//    CommandType.StoredProcedure, "SignIn", signInPara));
//  }

//  public int ChangePassword (string oldPassword, string newPassword, int userId)
//  {
//   object m_DBNull = Convert.DBNull;
//
//   SqlParameter[] para = {
//           new SqlParameter("@userId", userId),
//           new SqlParameter("@oldPassword", oldPassword),
//           new SqlParameter("@newPassword", newPassword),
//           new SqlParameter("@result", SqlDbType.Int, 8, ParameterDirection.Output,
//           true, 0, 0, "", DataRowVersion.Default, m_DBNull)
//          };
//   try
//   {
//    DAL.SQLHelper.ExecuteNonQuery(DAL.SQLHelper.CONN_STRING, CommandType.StoredProcedure, "ChangePassword", para);
//   }
//   catch
//   {
//    throw;
//   }
//
//   return Convert.ToInt32(para[3].Value);
//  }
//
//  public UserInfo GetUserInfo(string userId)
//  {
//   SqlParameter[] para = {
//           new SqlParameter("@userId", int.Parse(userId))
//          };
//  
//   SqlDataReader dr = DAL.SQLHelper.ExecuteReader(DAL.SQLHelper.CONN_STRING, CommandType.StoredProcedure, "GetUserInfo", para);
//
//   dr.Read();
//
//   UserInfo userInfo = new UserInfo();
//   userInfo.userRealName = dr["UserRealName"].ToString();
//   userInfo.zipcode = dr["zipcode"].ToString();
//   userInfo.address = dr["address"].ToString();
//   userInfo.email = dr["email"].ToString();
//   userInfo.sex = dr["sex"].ToString();
//
//   return userInfo;
//  }
//  
//  public int ChangeProfile(string userId, string userRealName, string address,
//   string zipCode, string email ,string sex)
//  {
//
//   SqlParameter[] para = {
//           new SqlParameter("@userId", int.Parse(userId)),
//           new SqlParameter("@userRealName", userRealName),
//           new SqlParameter("@address", address),
//           new SqlParameter("@zipcode", zipCode),
//           new SqlParameter("@email", email),
//           new SqlParameter("@sex", sex)
//          };
//
//   return DAL.SQLHelper.ExecuteNonQuery(DAL.SQLHelper.CONN_STRING, CommandType.StoredProcedure,
//    "EditAcount", para);
//  }
//
//  public int AddNewUser(string userName, string password, string question, string answer)
//  {
//   object m_DBNull = Convert.DBNull;
//
//   SqlParameter[] para = {
//           new SqlParameter("@userName", userName),
//           new SqlParameter("@Password", password),
//           new SqlParameter("@question", question),
//           new SqlParameter("@answer", answer),
//           new SqlParameter("@result", SqlDbType.Int, 8, ParameterDirection.Output,
//           true, 0, 0, "", DataRowVersion.Default, m_DBNull)
//          };
//
//   try
//   {
//    DAL.SQLHelper.ExecuteNonQuery(DAL.SQLHelper.CONN_STRING, CommandType.StoredProcedure,
//     "AddNewUser", para);
//   }
//   catch
//   {
//    throw;
//   }
//
//   return Convert.ToInt32(para[4].Value);
//  }


  public int GetBackPassword(string userName, string question, string answer, string email)
  {
   //string P_Con=ConfigurationSettings.
   object m_DBNull = Convert.DBNull;
   //获得新的随机密码
   string newPassword = MakePassword(6);
   SystemTool tool=new SystemTool();
   //定义存储过程参数
   SqlParameter[] para = {
           new SqlParameter("@userid", userName),
           new SqlParameter("@passquestion", question),
           new SqlParameter("@passanswer", answer),
           new SqlParameter("@newPassword", tool.Encrypt(newPassword,16)),
           new SqlParameter("@result", SqlDbType.Int, 8, ParameterDirection.Output,
           true, 0, 0, "", DataRowVersion.Default, m_DBNull)
          };
  
   //执行存储过程
   try
   {
    //DAL.SQLHelper.ExecuteNonQuery(DAL.SQLHelper.CONN_STRING, CommandType.StoredProcedure,"Pr_GetBackPwd", para);
    
    SQLHelper.ExecuteNonQuery(P_Con,CommandType.StoredProcedure,"Pr_GetBackPwd",para);
    
   }
   catch
   {
    throw new Exception("邮件无法发送!");
   }
   //获得输出参数的值
   int result = Convert.ToInt32(para[4].Value);
   //如果密码保护资料填写正确
   if (result == 1)
   {
    //从Web.config获取发信人地址、邮件标题、邮件用户名和密码以及SmtpServer
    string sender = System.Configuration.ConfigurationSettings.AppSettings["mailSender"];
    string title = System.Configuration.ConfigurationSettings.AppSettings["mailTitle"];
    string mailUser =  System.Configuration.ConfigurationSettings.AppSettings["mailUser"];
    string mailPwd = System.Configuration.ConfigurationSettings.AppSettings["mailPwd"];
    string smtpServer = System.Configuration.ConfigurationSettings.AppSettings["mailSmtpServer"];
  
    //发信
    try
    {
     Mail.CDOsendmail(sender, email, title, "您在半岛人才网的密码已找回,新密码为"+newPassword
      , mailUser, mailPwd, smtpServer);
    }
    catch(Exception ex)
    {
     throw new Exception(ex.Message);
    }
   }

   return result;
  }


  //随机生成密码
  private static string MakePassword(int pwdLength)
  {
   //声明要返回的字符串
   string tmpstr = "";
   //密码中包含的字符数组
   string pwdchars="abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
   //数组索引随机数
   int iRandNum;
   //随机数生成器
   Random rnd = new Random();
   for(int i=0;i<pwdLength;i++)
   {
    //Random类的Next方法生成一个指定范围的随机数
    iRandNum = rnd.Next(pwdchars.Length);
    //tmpstr随机添加一个字符
    tmpstr += pwdchars[iRandNum];
   }
   return tmpstr;
  }
 
  
 }
}

posted @ 2010-05-18 14:27  你妹的sb  阅读(1008)  评论(2编辑  收藏  举报
百度一下