1117 邮件验证

前段界面:

 <form id="form1" runat="server">
    请输入邮箱:<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:Button ID="Button2" runat="server" Text="Button" /><asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </form>

C#代码:

首先需要引用两个命名空间:

using System.Net;
using System.Net.Mail;

 protected void Page_Load(object sender, EventArgs e)
    {
        Button1.Click += Button1_Click;//发送验证码
        Button2.Click += Button2_Click;//验证验证码
    }

    void Button2_Click(object sender, EventArgs e)//验证码的验证
    {
        if (Session["YZM"].ToString() == TextBox2.Text.Trim())//判断验证
        {
            Label1.Text = "正确";
        }
        else { Label1.Text = "错误"; }
    }

    void Button1_Click(object sender, EventArgs e)//向输入的邮箱发送验证码
    {
        SmtpClient smtp = new SmtpClient("smtp.sina.cn");//服务器对象  
        MailAddress from=new MailAddress("");//发送者
        MailAddress to=new MailAddress(TextBox1.Text.Trim());//接受者
        MailMessage mess=new MailMessage(from,to);//发送对象
        mess.Subject = "来自呵呵的验证码";//邮件标题行
        string aaa="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";//验证码元素
        string YZM = "";
        Random r = new Random();//随机类
        for(int i=0;i<6;i++)//验证码取值
        {  
            YZM += aaa.Substring(r.Next(1, aaa.Length), 1);
        }
        Session["YZM"] = YZM;
        mess.Body = YZM;//邮件内容
        NetworkCredential nt = new NetworkCredential("", "");//凭证
        smtp.Credentials=nt;
        smtp.Send(mess);//发送
    }
原文地址:https://www.cnblogs.com/a12110303043/p/6072937.html