参考文档:https://blog.csdn.net/sD7O95O/article/details/124007107
安装nuget包
Install-Package NETCore.MailKit -Version 2.0.3
配置
配置 appsetting.json
我使用的是qq邮箱
"EmailOptions": { "SenderName": "系统邮件", //发送者名称,可在代码中重新替换 "FromAddress": "@qq.com", //发件者邮箱 "ToAddress": "", //接收人邮箱 "Host": "smtp.qq.com", //主机 "Port": 465, //端口 阿里云默认25端口不开放,需要使用SSL的465端口 "UserName": "@qq.com", //发件邮箱账号 "Password": "" //发件邮箱密码 },
添加 EmailOptions
public class EmailOptions { public string FromAddress { get; set; } public string ToAddress { get; set; } public string Host { get; set; } public string UserName { get; set; } public string Password { get; set; } }
配置 Startup
#region 注册邮件服务 services.Configure<EmailOptions>(Configuration.GetSection("EmailOptions")); services.AddMailKit(optionBuilder => { optionBuilder.UseMailKit(new MailKitOptions() { Server = Configuration.GetValue<string>("EmailOptions:Host"), Port = Configuration.GetValue<int>("EmailOptions:Port"), SenderName = Configuration.GetValue<string>("EmailOptions:SenderName"), SenderEmail = Configuration.GetValue<string>("EmailOptions:FromAddress"), // can be optional with no authentication Account = Configuration.GetValue<string>("EmailOptions:UserName"), Password = Configuration.GetValue<string>("EmailOptions:Password"), // enable ssl or tls Security = true }); }); #endregion 注册邮件服务
发送邮件
/// <summary> /// 会员注册邮箱验证码 /// </summary> /// <param name="emial"></param> /// <returns></returns> [AllowAnonymous] [HttpGet, Route("API/ValidateCodeEmail")] public async Task<object> ValidateCodeEmail(string email) { try { string code = ""; VierificationCodeServices _vierificationCodeServices = new VierificationCodeServices(); System.IO.MemoryStream ms = _vierificationCodeServices.Create(out code); new CacheHelper().AddCaChe("webRegisterValidateCode", code); if (string.IsNullOrEmpty(email)) { result.success = false; result.msg = "请输入正确的邮箱"; return result; } Regex emailRegex = new Regex(@"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"); if (!emailRegex.IsMatch(email)) { result.success = false; result.msg = "请输入正确的邮箱"; return result; } string subj = "绑定邮箱帐号验证码"; string bodys = $"您好,本次操作校验码为{code}。您正在使用绑定邮箱帐号,如非本人操作,请忽略。"; var sendInfo = new SenderInfo { SenderEmail = emailoptions.FromAddress, SenderName = "邮箱帐号验证码", }; emailoptions.ToAddress = email; await _EmailService.SendAsync(emailoptions.ToAddress, subj, bodys, false); result.success = true; //发送邮件 return result; } catch (Exception ex) { result.success = false; result.msg = "发送信息失败,请检查邮箱" + ex.Message; return result; } }
标签:core,string,EmailOptions,result,邮箱,net,Configuration,public,邮件 From: https://www.cnblogs.com/misakayoucn/p/17991488