一:前端页面添加一个邮件发送按钮(button控件)
<div>
<asp:Button ID="Button1" runat="server" Text="发送验证码" OnClick="Button1_Click" />
</div>
二:后台对button控件的Button1_Click事件进行操作
protected void Button1_Click(object sender, EventArgs e)
{
SmtpClient client = new SmtpClient("smtp.qq.com", 587);
Random Rdm = new Random();
//产生0到100000的随机数
int iRdm = Rdm.Next(0000, 99999);
MailMessage msg = new MailMessage("A", "B", "验证码", iRdm.ToString());
client.UseDefaultCredentials = false;
System.Net.NetworkCredential basicAuthenticationInfo =
new System.Net.NetworkCredential("A", "C");
client.Credentials = basicAuthenticationInfo;
client.EnableSsl = true;
client.Send(msg);
}
备注:1. SmtpClient client = new SmtpClient("邮箱服务器类型", 端口号);
2. 587是QQ邮箱对应的smtp服务器端口,若使用其他邮箱则去百度端口号(如@163.com端口号为25);
3. A:发送消息的邮箱;B:接受信息的邮箱;C:开启SMTP的密码
4. MailMessage msg = new MailMessage("发信息的邮箱", "接收的邮箱", "主题", iRdm.ToString());
5. System.Net.NetworkCredential basicAuthenticationInfo =
new System.Net.NetworkCredential("发信息的邮箱", "开启SMTP的密码");
6:.确保邮箱已经开启了SMTP服务,开启后会给出一串编码就是smtp服务密码,后台填入编码
7.引用命名空间 using System.Net.Mail;
protected void Button1_Click(object sender, EventArgs e)
{
SmtpClient client = new SmtpClient("smtp.qq.com", 587);
Random Rdm = new Random();
//产生0到100000的随机数
int iRdm = Rdm.Next(0000, 99999);
MailMessage msg = new MailMessage("A", "B", "验证码", iRdm.ToString());
client.UseDefaultCredentials = false;
System.Net.NetworkCredential basicAuthenticationInfo =
new System.Net.NetworkCredential("A", "C");
client.Credentials = basicAuthenticationInfo;
client.EnableSsl = true;
client.Send(msg);
}