C# Winfrom 发送邮件验证码&Timer控件

邮件发送:

//定义一个全局的string类型的验证码;
string yzm = "";
//定义一个字符串,这里面包含所有需要的验证码的元素;
string a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
//以下写在按钮的点击事件内
//实例化随机数
Random b = new Random();
yzm = "";
//循环6次得到一个随机的六位数验证码
 for (int i = 0; i < 6; i++)
 {
    yzm = yzm + a.Substring(b.Next(0, a.Length), 1);
 }
//创建服务器对象
SmtpClient smtp = new SmtpClient("smtp.sina.cn");
//创建发件人的邮箱
MailAddress ab = new MailAddress("xxxxx@sina.cn");
try
{
//获取文本框的收件人的邮箱
   MailAddress cd = new MailAddress(textBox1.Text);
//创建邮件对象,准备发送
   MailMessage mess = new MailMessage(ab, cd);
//邮件的标题
   mess.Subject = "邮件验证码";
//邮件的内容
   mess.Body = "您的验证码为:" + yzm + ",请在20分钟内验证,系统邮件请勿回复!";
//创建互联网安全证书
   NetworkCredential cred = new NetworkCredential("邮箱账号@sina.cn", "邮箱密码");
//将证书绑定到服务器对象以便服务器验证
   smtp.Credentials = cred;
//开始发送
    smtp.Send(mess);
//发送完成后按钮不可用
//                button3.Enabled = false;
//激活timer事件
//                timer1.Enabled = true;
//倒计时30秒
//                timer = 30;
    MessageBox.Show("发送成功");
}
catch
{
    MessageBox.Show("输入正确的邮箱格式!");

}

邮箱验证码验证:

if (yzm == textBox2.Text)
{
     MessageBox.Show("正确");
}
else
{
     MessageBox.Show("错误");
}

设置timer事件:

timer--;
button3.Text = "发送(" + timer + "";
if (timer <= 0)
{
     button3.Text = "发送";
     timer1.Enabled = false;
     button3.Enabled = true;
}
原文地址:https://www.cnblogs.com/xinchenhui/p/7932518.html