文章目录
#1.先看效果图
#1.1开通邮箱SMTP服务
#2.前端(vue+axios)
#2.1前端源码
<template>
<div class="hello">
<input type="email" v-model="msg" placeholder="xxxx.qq.com">
<input type="text" v-model="account" placeholder="">
<button @click="sendCheck">发送验证码</button>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data() {
return {
msg:"",
account:"",
}
},
methods: {
sendCheck(){
this.axios(
{
url:'http://localhost:51513/api/checkCode/checkCode', //改成你自己的就可以了
method:'post',
params:{
address:this.msg, //发送到指定邮箱
check:this.account //发送的验证码
}
}
).then(function(res)
{
if(res.data==1) //判断后端的返回值,来确定有没有发送邮件
{
console.log("发送成功")
}
}.bind(this))
}
},
}
</script>
#2.2安装并使用axios,
npm install --save axios (在终端安装)
#2.2.1在mian.js中引用axios
import axios from'axios'
Vue.prototype.axios=axios
#2.3发送请求
this.axios(
{
url:'http://localhost:51513/api/checkCode/checkCode', //改成你自己的就可以了
method:'post',
params:{
address:this.msg, //发送到指定邮箱
check:this.account //发送的验证码
}
}
).then(function(res)
{
if(res.data==1) //判断后端的返回值,来确定有没有发送邮件
{
console.log("发送成功")
}
}.bind(this))
}
#3.后端(asp.netcorewebapi)
#3.1asp.netcore配置跨域
#3.1.1在startup.cs中配置跨域
public void ConfigureServices(IServiceCollection services)
{
//处理跨域,我这里是允许任何的请求方式,请求头,域名
services.AddCors(o => o.AddPolicy("any", p => p.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()));
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
//使用配置好的服务
app.UseCors();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
#3.1.2在.controall(控制器)中使用跨域
[EnableCors("any")] //使用跨域
[Route("api/[controller]/[action]")] //可以把[action]去掉,访问到controller层即可
[ApiController]
#3.2asp.netcore中配置邮箱
public int checkCode(string address,string check)
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);//一定不能去掉,否则不支持gb2312编码格式
string smtp = "smtp.qq.com";//qq的SMTP服务器地址
SmtpClient _smtpClient = new SmtpClient();
_smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式
_smtpClient.Host = smtp; //指定SMTP服务器
_smtpClient.Credentials = new System.Net.NetworkCredential("2825408858@qq.com", "开通服务时的凭证");//设置用于验证发件人身份的凭据
MailMessage _mailMessage = new MailMessage();
//发件人,发件人名
_mailMessage.From = new MailAddress("2825408858@qq.com", "微软工作室");
//收件人
_mailMessage.To.Add(address);
_mailMessage.SubjectEncoding = System.Text.Encoding.GetEncoding("GB2312");//标题编码
_mailMessage.Subject = "验证码";//邮件主题
_mailMessage.Body = "验证码:" + check + ",请勿转发!";//邮件内容
_mailMessage.BodyEncoding = Encoding.GetEncoding("GB2312");//正文编码
_mailMessage.IsBodyHtml = true;//设置为HTML格式
_mailMessage.Priority = MailPriority.High;//优先级
_smtpClient.Send(_mailMessage);//发送邮件
return 1;
}