您的位置:首页 > 其它

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

2007-01-15 18:33 513 查看
第一步: 先配置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>
<system.web>

<!--Ajax-->
<httpHandlers>
<add verb="POST,GET" path="csharpwrapper/*.ashx" type="Ajax.PageHandlerFactory, Ajax" />
</httpHandlers>
<!-- 动态调试编译
设置 compilation debug="true" 以启用 ASPX 调试。否则,将此值设置为
false 将提高此应用程序的运行时性能。
设置 compilation debug="true" 以将调试符号(.pdb 信息)
插入到编译页中。因为这将创建执行起来
较慢的大文件,所以应该只在调试时将此值设置为 true,而在所有其他时候都设置为
false。有关更多信息,请参考有关
调试 ASP.NET 文件的文档。
-->
<compilation
defaultLanguage="c#"
debug="true"
/>

<!-- 自定义错误信息
设置 customErrors mode="On" 或 "RemoteOnly" 以启用自定义错误信息,或设置为 "Off" 以禁用自定义错误信息。
为每个要处理的错误添加 <error> 标记。

"On" 始终显示自定义(友好的)信息。
"Off" 始终显示详细的 ASP.NET 错误信息。
"RemoteOnly" 只对不在本地 Web 服务器上运行的
用户显示自定义(友好的)信息。出于安全目的,建议使用此设置,以便
不向远程客户端显示应用程序的详细信息。
-->
<customErrors
mode="Off" />


<!-- 身份验证
此节设置应用程序的身份验证策略。可能的模式是 "Windows"、
"Forms"、 "Passport" 和 "None"

"None" 不执行身份验证。
"Windows" IIS 根据应用程序的设置执行身份验证
(基本、简要或集成 Windows)。在 IIS 中必须禁用匿名访问。
"Forms" 您为用户提供一个输入凭据的自定义窗体(Web 页),然后
在您的应用程序中验证他们的身份。用户凭据标记存储在 Cookie 中。
"Passport" 身份验证是通过 Microsoft 的集中身份验证服务执行的,
它为成员站点提供单独登录和核心配置文件服务。
-->
<authentication mode="None" />

<!-- 授权
此节设置应用程序的授权策略。可以允许或拒绝不同的用户或角色访问
应用程序资源。通配符: "*" 表示任何人,"?" 表示匿名
(未经身份验证的)用户。
-->

<authorization>
<allow users="*" /> <!-- 允许所有用户 -->
<!-- <allow users="[逗号分隔的用户列表]"
roles="[逗号分隔的角色列表]"/>
<deny users="[逗号分隔的用户列表]"
roles="[逗号分隔的角色列表]"/>
-->
</authorization>

<!-- 应用程序级别跟踪记录
应用程序级别跟踪为应用程序中的每一页启用跟踪日志输出。
设置 trace enabled="true" 可以启用应用程序跟踪记录。如果 pageOutput="true",则
在每一页的底部显示跟踪信息。否则,可以通过浏览 Web 应用程序
根目录中的 "trace.axd" 页来查看
应用程序跟踪日志。
-->
<trace
enabled="false"
requestLimit="10"
pageOutput="false"
traceMode="SortByTime"
localOnly="true"
/>

<!-- 会话状态设置
默认情况下,ASP.NET 使用 Cookie 来标识哪些请求属于特定的会话。
如果 Cookie 不可用,则可以通过将会话标识符添加到 URL 来跟踪会话。
若要禁用 Cookie,请设置 sessionState cookieless="true"。
-->
<sessionState
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes"
cookieless="false"
timeout="20"
/>

<!-- 全球化
此节设置应用程序的全球化设置。
-->
<globalization
requestEncoding="utf-8"
responseEncoding="utf-8"
/>

</system.web>

</configuration>

第二步: 添加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[".Value]http://schemas.microsoft.com/cdo/configuration/sendusing"].Value = 2;
oFields[".Value=userName]http://schemas.microsoft.com/cdo/configuration/sendusername"].Value=userName;
oFields[".Value=password]http://schemas.microsoft.com/cdo/configuration/sendpassword"].Value=password;
oFields[".Value=1]http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"].Value=1;
oFields[".Value=0x0804]http://schemas.microsoft.com/cdo/configuration/languagecode"].Value=0x0804;
oFields[".Value=smtpServer]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> 
  <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;
}


}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: