C# WinForm 使用SMTP协议发送QQ邮箱验证码


前言

  在程序设计中,发送验证码是常见的一个功能,用户在注册账号或忘记密码时,通常需要发送验证码到手机或邮箱来验证身份,此篇博客介绍在C#WinForm中使用SMTP协议发送QQ邮箱验证码(其他邮箱方法类似)。
  关于"发送手机验证码",可以参考我这篇文章:使用SMS接口发送手机验证码


功能实现步骤

一、获取QQ邮箱授权码

授权码就是一个QQ邮箱推出的、长度为16位的、用于登录第三方客户端的专用密码。

  获取QQ邮箱授权码的方法


二、功能界面

在这里插入图片描述


三、创建发送邮箱验证码的类

QQ邮箱的SMTP使用了SSL加密,必须启用SSL加密,并且指定端口才能发送。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//发送邮件需要引用的命名空间
using System.Net.Mail;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace MailVeriCode
{
    public class MailVeriCodeClass
    {
        #region  邮箱验证码功能
        /// <summary>
        ///  生成随机验证码
        /// </summary>
        /// <param name="CodeLength">验证码长度</param>
        public static string CreateRandomMailCode(int CodeLength)
        {
            int randNum;
            char code;
            string randomCode = String.Empty;//随机验证码

            //生成一定长度的随机验证码       
            //Random random = new Random();//生成随机数对象
            for (int i = 0; i < CodeLength; i++)
            {
                //利用GUID生成6位随机数      
                byte[] buffer = Guid.NewGuid().ToByteArray();//生成字节数组
                int seed = BitConverter.ToInt32(buffer, 0);//利用BitConvert方法把字节数组转换为整数
                Random random = new Random(seed);//以生成的整数作为随机种子
                randNum = random.Next();

                //randNum = random.Next();                
                if (randNum % 3 == 1)
                {
                    code = (char)('A' + (char)(randNum % 26));//随机大写字母
                }
                else if (randNum % 3 == 2)
                {
                    code = (char)('a' + (char)(randNum % 26));//随机小写字母
                }
                else
                {
                    code = (char)('0' + (char)(randNum % 10));//随机数字
                }
                randomCode += code.ToString();
            }
            return randomCode;
        }


        /// <summary>
        ///  发送邮件验证码
        /// </summary>
        /// <param name="MyEmailAddress">发件人邮箱地址</param>
        /// <param name="RecEmailAddress">收件人邮箱地址</param>
        /// <param name="Subject">邮件主题</param>
        /// <param name="MailContent">邮件内容</param>
        /// <param name="AuthorizationCode">邮箱授权码</param>
        /// <returns></returns>
        public static bool SendMailMessage(string MyEmailAddress, string RecEmailAddress, string Subject, string Body, string AuthorizationCode)
        {
            MailMessage mail = new MailMessage();
            mail.From = new MailAddress(MyEmailAddress);//发件人邮箱地址
            mail.To.Add(new MailAddress(RecEmailAddress));//收件人邮箱地址
            mail.Subject = Subject;//邮件标题
            mail.Body = Body;  //邮件内容  
            mail.Priority = MailPriority.High;//优先级

            SmtpClient client = new SmtpClient();//qq邮箱:smtp.qq.com;126邮箱:smtp.126.com              
            client.Host = "smtp.qq.com";
            client.Port = 587;//SMTP端口465或587
            client.EnableSsl = true;//使用安全加密SSL连接  
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.Credentials = new NetworkCredential(MyEmailAddress, AuthorizationCode);//验证发件人身份(发件人邮箱,邮箱授权码);                   
            
            try
            {
                client.Send(mail);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "发送失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            return true;
        }


        /// <summary>
        ///  验证QQ邮箱
        /// </summary>
        /// <param name="mail">邮箱</param>
        /// <returns></returns>
        public static bool CheckMail(string mail)
        {
            string str = @"^[1-9][0-9]{4,}@qq.com$";
            Regex mReg = new Regex(str);

            if (mReg.IsMatch(mail))
            {
                return true;
            }
            return false;
        }
        #endregion
    }
}

四、在From1中调用类中的函数,实现功能

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//需要引用的命名空间
using System.Net.Mail;
using System.Net;

namespace MailVeriCode
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        /// <summary>
        ///  发送邮箱验证码
        /// </summary>    
        int seconds1 = 60;//倒计时60s
        int seconds2 = 60 * 5;//验证码有效时间5分钟
        string strMailVeriCode;   
        private void btnMailVeriCode_Click(object sender, EventArgs e)
        {
            string recEMailAddress = txtMail.Text.Trim();//收件人邮箱             

            strMailVeriCode = MailVeriCodeClass.CreateRandomMailCode(6);
            string strBody = "验证码:" + strMailVeriCode + ",5分钟内有效,请勿泄漏于他人。如非本人操作,请忽略。系统邮件请勿回复。";//邮件内容            
            string strSubject = "【代码科技】注册验证";//邮件标题
            string strMyEmailAddress = "XXXXXXX";//发件人邮箱
            string strAuthorizationCode = "XXXXXX";//邮箱授权码

            if (string.IsNullOrEmpty(recEMailAddress))//判断是否输入了邮箱
            {
                MessageBox.Show("请输入邮箱!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtMail.Focus();
            }
            else if (MailVeriCodeClass.CheckMail(recEMailAddress) == false)//判断邮箱格式是否正确
            {
                MessageBox.Show("您输入的QQ邮箱有误,请重新输入!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                txtMail.Focus();
                return;
            }
            else//发送验证码
            {                
                //发送
                if (MailVeriCodeClass.SendMailMessage(strMyEmailAddress, recEMailAddress, strSubject, strBody, strAuthorizationCode) == true)
                {
                    btnMailVeriCode.Enabled = false;

                    //计时器初始化              
                    timer1.Interval = 1000;
                    timer1.Start();
                    timer2.Interval = 1000;
                    timer2.Start();                    

                }
                else
                {               
                    txtMail.Focus();
                }
            }
        }


        /// <summary>
        ///  倒计时—邮箱验证码1分钟只能点击发送1次
        /// </summary> 
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (seconds1 > 0)
            {
                seconds1--;
                btnMailVeriCode.Text = "剩余" + seconds1.ToString() + "秒";
            }
            else
            {
                timer1.Stop();

                btnMailVeriCode.Text = "获取验证码";
                btnMailVeriCode.Enabled = true;
            }
        }


        /// <summary>
        ///  手机SMS验证码5分钟内有效;但是如果有新的验证码出现,旧验证码就会失效        
        /// </summary>
        private void timer2_Tick(object sender, EventArgs e)
        {
            if (seconds2 == 0)
            {
                timer2.Stop();

                //旧的验证码过期,生成一个新的验证码
                strMailVeriCode = MailVeriCodeClass.CreateRandomMailCode(6);
            }
        }


        /// <summary>
        ///  确认邮箱验证码
        /// </summary>      
        private void btnConfirm_Click(object sender, EventArgs e)
        {
            string mailVeriCode = txtMailVeriCode.Text.Trim();//邮箱验证码  

            if (string.IsNullOrEmpty(mailVeriCode) == true)
            {
                MessageBox.Show("请输入验证码", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtMailVeriCode.Focus();
            }
            else if (mailVeriCode.ToLower() != strMailVeriCode.ToLower())//判断邮箱验证码是否输入正确;不区分字母大小写
            {
                MessageBox.Show("您输入的验证码有误!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                txtMailVeriCode.Focus();
                return;
            }
            else
            {
                MessageBox.Show("验证成功!");
            }
        }
    }
}

参考文章:
https://blog.csdn.net/weixin_42449444/article/details/90722070

  • 11
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
WinForm 中实现发送邮箱验证码倒计时按钮可以通过以下步骤完成: 1. 在窗体中添加一个按钮和一个文本框,用于输入邮箱地址和显示倒计时信息。 2. 在按钮的 Click 事件中,先进行邮箱地址的验证,如果验证不通过,则弹出提示框。 3. 如果验证通过,则调用发送邮件的方法,并开启一个计时器,用于实现倒计时功能。 4. 在计时器的 Tick 事件中,更新倒计时信息,并在倒计时结束时停止计时器。 以下是示例代码: ```csharp private int countDown = 60; // 倒计时时间(秒) private Timer timer = new Timer(); private void btnSend_Click(object sender, EventArgs e) { string email = txtEmail.Text.Trim(); if (!Regex.IsMatch(email, @"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$")) { MessageBox.Show("邮箱地址格式不正确!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } // 调用发送邮件的方法 SendEmail(email); // 开启计时器 countDown = 60; timer.Interval = 1000; timer.Tick += new EventHandler(timer_Tick); timer.Start(); } private void timer_Tick(object sender, EventArgs e) { countDown--; if (countDown == 0) { timer.Stop(); btnSend.Enabled = true; btnSend.Text = "发送验证码"; } else { btnSend.Enabled = false; btnSend.Text = string.Format("{0}秒后重发", countDown); } } ``` 在上述代码中,SendEmail 方法需要根据具体情况进行实现,用于发送邮件验证码。在计时器的 Tick 事件中,根据倒计时时间更新按钮的文本和状态,并在倒计时结束时停止计时器。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值