邮箱验证码

<%@ Page Language="C#" Debug="true" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>&nbsp;箱:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="发送验证码" /><br /><br />
        验证码:<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <asp:Label ID="Label1" runat="server" Text="" ForeColor="Red"></asp:Label><br /><br />
        <asp:Button ID="Button2" runat="server" Text="验证" />
    </div>
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Mail;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Button1.Click += Button1_Click;
        Button2.Click += Button2_Click;
    }

    //发送按钮
    void Button1_Click(object sender, EventArgs e)
    {
        //创建外部的smtp服务客户端对象
        SmtpClient smtp = new SmtpClient("smtp.sina.cn");

        //创建证书对象
        NetworkCredential cred = new NetworkCredential("18560812711@sina.cn", "hq1234561");

        //服务器证书指向
        smtp.Credentials = cred;

        //验证码
        Random r = new Random();
        string str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        string yzm = str.Substring(r.Next(0 ,str.Length ),4);
        Session["yzm"] = yzm;

        //标题
        string subject = "来自XX官网的邮件验证";

        //内容
        string context = "您的邮箱验证码为[" + yzm + "],请在20分钟内填写验证!此邮件为系统邮件,勿回复!";

        //将邮件发送到指定服务器
        smtp.Send("18560812711@sina.cn", TextBox1.Text.Trim(), subject, context);
    }

    //验证按钮
    void Button2_Click(object sender, EventArgs e)
    {
        if (TextBox2.Text.ToUpper() == Session["yzm"].ToString().ToUpper())
        {
            Label1.Text = "验证码错误";
        }
        else { Label1.Text = ""; }
    }

}

 

posted @ 2016-10-28 22:45  庚xiao午  阅读(330)  评论(0编辑  收藏  举报