如何用户注册时添加邮箱验证功能

第一步,向验证邮箱发送邮件

to:接收邮件地址

subject:邮件标题

body:邮件内容(body中带有执行页面的URL信息等,当点击这个链接是能够执行所有请求的页面地址)

 public bool Send(string to, string subject, string body)

{  

   

    SmtpClient smtp = new SmtpClient();
    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
    if (_port != 25)
      smtp.EnableSsl = true;

    smtp.Host = _host;//邮件地址
    smtp.Port = _port;//邮件端口号
    smtp.Credentials = new NetworkCredential(_username, _password);//username:发送邮件的账号,password:发送邮件的密码

    MailMessage mm = new MailMessage();
    mm.Priority = MailPriority.Normal;
    mm.From = new MailAddress(_from, subject, _bodyencoding);//from:获取发件人地址,//subject:邮件标题//bodyencoding:邮件内容编码
    mm.To.Add(to);
    mm.Subject = subject;
    mm.Body = body;
    mm.BodyEncoding = _bodyencoding;
    mm.IsBodyHtml = _isbodyhtml;

    try
      {
        smtp.Send(mm);
      }
    catch
      {
        return false;
      }

    return true;

}

 

第二步:就是点击发送到邮箱中的链接地址进行邮箱验证,通过,邮箱更新到数据库()

public ActionResult UpdateEmail()
{
    string url = WebHelper.GetQueryString("url");

    //数组第一项为uid,第二项为邮箱名,第三项为验证时间,第四项为随机值
    string[] result = StringHelper.SplitString(url);
    if (result.Length != 4)
      return HttpNotFound();

    int uid = TypeHelper.StringToInt(result[0]);
    string email = result[1];
    DateTime time = TypeHelper.StringToDateTime(result[2]);

    //判断当前用户是否为验证用户
    if (uid != WorkContext.Uid)  //判断验证的的用户名是否和邮箱中获取的用户名一致,这里的WorkContent个人定义的一个Model,存放临时信息。
      return HttpNotFound();
    //判断验证时间是否过时
    if (DateTime.Now.AddMinutes(-30) > time)
      return PromptView("此链接已经失效,请重新验证");
    int tempUid = Users.GetUidByEmail(email);
    if (tempUid > 0 && tempUid != WorkContext.Uid)
      return PromptView("此链接已经失效,邮箱已经存在");

    //更新邮箱名
    Users.UpdateUserEmailByUid(WorkContext.Uid, email);//更新数据库邮箱数据自己写
    
    return RedirectToAction("safesuccess", new RouteValueDictionary { { "act", "updateEmail" }, { "remark", email } });//返回验证成功的页面,这个自己写

}

posted @ 2015-11-02 10:53  云之星海  阅读(1498)  评论(0编辑  收藏  举报