首页 > 其他分享 >.net core 注册邮件服务实现发送邮件

.net core 注册邮件服务实现发送邮件

时间:2024-01-27 15:37:14浏览次数:28  
标签:core string EmailOptions result 邮箱 net Configuration public 邮件

参考文档: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

相关文章

  • C# .NET 中 LINQ to Entities查询中使用时转换为数据库函数的CLR方法(EF.Functions)
    EF.Functions映射由于并非所有数据库函数都有等效的C#函数,因此EFCore提供程序提供了特殊的C#方法来调用某些数据库函数。这些方法通过EF.Functions定义为扩展方法来用于LINQ查询中。这些方法是特定于提供程序的,因为它们与特定数据库函数密切相关。因此,适用于某个......
  • .net core 静态文件的访问权限控制(UseStaticFiles)
    官方文档:https://learn.microsoft.com/zh-cn/aspnet/core/fundamentals/static-files?view=aspnetcore-8.0&viewFallbackFrom=aspnetcore-2.2wwwroot中的文件,可以在Startup类的Configure方法中添加以下语句:app.UseStaticFiles();默认情况下,诸如HTML、css、图像、js之类的静态资......
  • .net core 配置跨域访问
    在Startup类里面先配置ConfigureServices方法#region跨域访问string[]coreslink=Configuration.GetSection("AppSetting:Cores").Value.Split(',');//services.AddCors(options=>//{//options.AddPolicy("all&quo......
  • Kubernetes 推荐学习资料 课程 视频
    以下是一些推荐的Kubernetes学习资料、课程和视频:学习资料:Kubernetes官方文档:https://kubernetes.io/docs/home/《Kubernetes操作指南》(KubernetesUp&Running)一书,由KelseyHightower、BrendanBurns、JoeBeda著。《KubernetesinAction》一书,由MarkoLuksa著。《Kuberne......
  • 使用EtherNET转Profinet网关配置EtherNET/IP地址说明
    EtherNET转Profinet网关配置EtherNET/IP地址是将两种网络之间的连接进行设置和调整,以便实现数据的传输和信息的交互。这个过程中,需要对EtherNET/IP地址进行配置,以确保数据能够正确地在网络之间传递。通过配置EtherNET/IP地址,可以准确地指定物理设备的位置和通信路径,从而使数据传输......
  • 使用 Asp.net core webapi 集成配置系统,提高程序的灵活和可维护性
    前言:什么是集成配置系统?集成配置系统的主要目的是将应用程序的配置信息与代码分离,使得配置信息可以在不需要修改代码的情况下进行更改。这样可以提高应用程序的灵活性和可维护性。ASP.NETCore提供了一种灵活的配置系统,可以轻松地将配置信息从不同的来源加载到应用程序中,并且......
  • .NET Core 6.0 Windows部署
    varoptions=newWebApplicationOptions{Args=args,//这是因为从Windows中调用GetCurrentDirectory会返回:C:\WINDOWS\system32//需要注意使用了WindowsService部署,就不能使用Console类,否则会报错ContentRootPath=WindowsServiceHelpers.IsWindowsServi......
  • CSharp: UglyToad.PdfPig int .net8
     /*IDE:VS202217.5OS:windows10.net:8.0生成PDF文档,从PDF文档中获取文字内容控制台下测试*///Seehttps://aka.ms/new-console-templateformoreinformationusingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Xml.L......
  • CAN转PROFINET新应用,节能降本又高效,AGV行业西门子PLC与CAN驱动系统连接通信解决方案
    大家好,我今天给大家讲解一个AGV行业西门子PLC与CAN驱动系统连接通信解决方案(CAN转PROFINET)随着工厂自动化发展以及柔性制造系统、自动化立体仓库的广泛应用,已作为管理离散型装配、物流、仓储等系统不可或缺的自动化搬运装卸工具,智能化AGV系统可根据ERP订单进行仓库配料、分料、产......
  • k8s .netcore webapi
    .netcorewebapi迁移到到k8s1.  kcreatedeploymentaaa--image=aaa-image:1.2 -r=2, 然后把生成的deploy,-oyaml,删除不必要信息,保存为yamlapiVersion:apps/v1kind:Deploymentmetadata: labels:  app:my-app name:my-app namespace:app-ns......