C# WinForm 使用SMTP协议发送QQ邮箱验证码
文章来自:https://blog.csdn.net/IT_xiao_guang_guang/article/details/104336604
前言
在程序设计中,发送验证码是常见的一个功能,用户在注册账号或忘记密码时,通常需要发送验证码到手机或邮箱来验证身份,此篇博客介绍在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
==================================================
本文来自作者:菜鸟学飞ing去看世界
转载请注明本文链接:https://www.cnblogs.com/xggbest/p/12317628.html
限于本人水平,如果文章和代码有表述不当之处,还请不吝赐教!