ASP.Net注册时使用邮箱激活验证
激活验证主要实现的功能是:
当用户在注册页面注册数据时,向用户注册的邮箱发送一条激活链接,当用户点击此链接时用户注册的账号才能被激活,否则的话即使在登陆界面输入正确的用户名和密码也不能登陆。
using System;
using System.Collections.Generic;using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Net;
using System.Net.Mail;
namespace ValidateEmail
{
public partial class WebForm1 : System.Web.UI.Page
{
string sqlstr=ConfigurationManager.ConnectionStrings["sqlstr"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogon_Click(object sender, EventArgs e)
{
using (SqlConnection sqlcnn=new SqlConnection(sqlstr))
{
using (SqlCommand sqlcmm=sqlcnn.CreateCommand())
{
sqlcmm.CommandText = "insert into T_mail(id,username,userpas,mail)values(@id,@username,@userpas,@mail)";
sqlcmm.Parameters.AddWithValue("@id",System.Guid.NewGuid());//向数据库中插入GUID
sqlcmm.Parameters.AddWithValue("@username",this.txtUerName.Text);
sqlcmm.Parameters.AddWithValue("@userpas",this.txtPassword.Text);
sqlcmm.Parameters.AddWithValue("@mail",this.txtMail.Text);
sqlcnn.Open();
int i = sqlcmm.ExecuteNonQuery();
if (i > 0)
{
SendMail();
Response.Write("<script>alert('注册成功,请去您的邮箱进行激活!')</script>");
}
else
{
Response.Write("<script>alert('注册失败!')</script>");
}
}
}
}
private void SendMail()
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress("1607977350@qq.com"); //发件人的邮箱地址
msg.Subject = "*欢迎您的注册*"; //邮件主题
msg.Body = "<a href='http://localhost:38966/WebForm2.aspx?name="+this.txtUerName.Text+"'>点击激活您的账号</a>";//邮件正文
msg.To.Add(this.txtMail.Text);
msg.IsBodyHtml = true; //邮件正文是否支持html的值
SmtpClient sc = new SmtpClient();
sc.Host = "smtp.qq.com";
sc.Port = 25;
NetworkCredential nc = new NetworkCredential("1607977350", "********"); //验证凭据 1607977350:是邮箱账号,********:是邮箱密码
sc.Credentials = nc;
sc.Send(msg);
}
}
}