public static IServiceCollection AddEmail(this IServiceCollection services, IConfiguration configuration) { services.AddMailKit(optionBuilder => { var mailKitOptions = new MailKitOptions() { // get options from secrets.json Server = configuration.GetValue <string>("Email:Server"), Port = configuration.GetValue <int>("Email:Port"), SenderName = configuration.GetValue <string>("Email:SenderName"), SenderEmail = configuration.GetValue <string>("Email:SenderEmail"), // can be optional with no authentication Account = configuration.GetValue <string>("Email:Account"), Password = configuration.GetValue <string>("Email:Password"), Security = configuration.GetValue <bool>("Email:Security") }; if (mailKitOptions.Server == null) { throw new InvalidOperationException("Please specify SmtpServer in appsettings"); } if (mailKitOptions.Port == 0) { throw new InvalidOperationException("Please specify Smtp port in appsettings"); } if (mailKitOptions.SenderEmail == null) { throw new InvalidOperationException("Please specify SenderEmail in appsettings"); } optionBuilder.UseMailKit(mailKitOptions); }); services.AddScoped <IAppEmailService, AppEmailService>(); return(services); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddDbContext <AppDbContext>(config => { config.UseInMemoryDatabase("Memory"); }); //Add identity registers the services services.AddIdentity <IdentityUser, IdentityRole>(Config => { Config.Password.RequiredLength = 4; Config.Password.RequireDigit = false; Config.Password.RequireNonAlphanumeric = false; Config.Password.RequireUppercase = false; Config.SignIn.RequireConfirmedAccount = true; }) .AddEntityFrameworkStores <AppDbContext>() .AddDefaultTokenProviders(); services.ConfigureApplicationCookie(config => { config.Cookie.Name = "Identity.Cookie"; config.LoginPath = "/Home/Login"; }); var mailKitOptions = _config.GetSection("Email").Get <MailKitOptions>(); services.AddMailKit(config => { var options = new MailKitOptions(); config.UseMailKit(mailKitOptions); }); services.AddControllersWithViews(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // services.Configure<CookiePolicyOptions>(options => // { // // This lambda determines whether user consent for non-essential cookies is needed for a given request. // options.CheckConsentNeeded = context => true; // options.MinimumSameSitePolicy = SameSiteMode.None; // }); services.AddDbContext <ApplicationDbContext>(options => options.UseSqlite( Configuration.GetConnectionString("DefaultConnection"))); services.AddDefaultIdentity <IdentityUser>(options => { options.SignIn.RequireConfirmedEmail = true; }) .AddEntityFrameworkStores <ApplicationDbContext>(); // services.AddAuthentication("CookieAuth") // .AddCookie("CookieAuth", config => { // config.Cookie.Name = "Scarlet.Cookie"; // }); services.AddControllersWithViews(); services.AddRazorPages(); var mailKitOptions = Configuration.GetSection("Email").Get <MailKitOptions>(); services.AddMailKit(config => { var options = new MailKitOptions(); config.UseMailKit(mailKitOptions); }); }
public ProductAddedHandler(MailKitOptions options, IMessagesService messagesService, IUserService userService, ILogger <ProductAddedHandler> logger) { _options = options; _messagesService = messagesService; _userService = userService; _logger = logger; }
/// <summary> /// Add email service to DI /// </summary> /// <param name="options"></param> /// <param name="lifetime"></param> public IMailKitOptionsBuilder UseMailKit(MailKitOptions options, ServiceLifetime lifetime = ServiceLifetime.Scoped) { ServiceCollection.TryAddSingleton <IMailKitProvider>(new MailKitProvider(options)); ServiceCollection.TryAdd(new ServiceDescriptor(typeof(IEmailService), typeof(EmailService), lifetime)); return(this); }
public EmailWorkerService( IConfiguration config, ISerializationProvider serializationProvider, IRabbitService rabbitService, ILogger <EmailWorkerService> logger = null) { Guard.AgainstNull(config, nameof(config)); Guard.AgainstNull(rabbitService, nameof(rabbitService)); Guard.AgainstNull(serializationProvider, nameof(serializationProvider)); _config = config; _serializationProvider = serializationProvider; _rabbitService = rabbitService; _logger = logger; var mailKitOptions = new MailKitOptions { // Use Papercut Smtp for local testing! // https://github.com/ChangemakerStudios/Papercut-SMTP/releases Server = _config.GetValue <string>("HouseofCat:EmailService:SmtpHost"), Port = _config.GetValue <int>("HouseofCat:EmailService:SmtpPort"), SenderName = _config.GetValue <string>("HouseofCat:EmailService:SenderName"), SenderEmail = _config.GetValue <string>("HouseofCat:EmailService:SenderEmail"), //Account = Configuration.GetValue<string>("Email:Account"), //Password = Configuration.GetValue<string>("Email:Password"), //Security = Configuration.GetValue<bool>("Email:EnableTls") }; var provider = new MailKitProvider(mailKitOptions); _emailService = new EmailService(provider); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddIdentity <Player, AppRole>(options => { options.User.RequireUniqueEmail = true; options.SignIn.RequireConfirmedEmail = true; options.SignIn.RequireConfirmedPhoneNumber = false; }).AddEntityFrameworkStores <BgaContext>().AddDefaultTokenProviders(); services.AddDbContext <BgaContext>(options => options.UseLazyLoadingProxies().UseSqlServer(Configuration.GetConnectionString("BgaContext"))); MailKitOptions mailKitOprion = Configuration.GetSection("Email").Get <MailKitOptions>(); services.AddMailKit(config => config.UseMailKit(mailKitOprion)); services.Configure <RouteOptions>(routeOptions => { routeOptions.ConstraintMap.Add("alphanumeric", typeof(AlphanumericConstraint)); }); services.AddScoped <GameRepository, GameRepository>(); services.AddScoped <PartRepository, PartRepository>(); services.AddScoped <PlayerRepository, PlayerRepository>(); services.AddScoped <PartPlayerRepository, PartPlayerRepository>(); }
public OrderCreatedHandler(MailKitOptions options, ICustomersService customersService, IMessagesService messageServices) { _options = options; _customersService = customersService; _messageService = messageServices; }
public AccountService(IAuditBaseRepository <LinUser, long> userRepository, IEmailSender emailSender, IOptions <MailKitOptions> options, IUserIdentityService userIdentityService) { _userRepository = userRepository; _emailSender = emailSender; _mailKitOptions = options.Value; _userIdentityService = userIdentityService; }
public OrderCreatedIntegrationEventHandler( IOptions <MailKitOptions> mailSettings, IOptions <MailSendOptions> mailOptions, IEMailService emailService, ILogger <OrderCreatedIntegrationEventHandler> logger) { _mailSettings = mailSettings.Value; _mailOptions = mailOptions.Value; _emailService = emailService; _logger = logger ?? throw new ArgumentNullException(nameof(logger)); }
public static void AddServices(this IServiceCollection services, IConfiguration configuration) { var types = typeof(ServiceCollectionExtensions).Assembly.GetTypes(); var svcTypes = types .Where(x => x.FullName.Contains(".Impl.", StringComparison.InvariantCultureIgnoreCase)) .ToList(); foreach (var t in svcTypes) { foreach (var interf in t.GetInterfaces()) { services.AddScoped(interf, t); } } var singletons = types.Where(x => !x.IsAbstract && x.IsClass && typeof(ISingleton).IsAssignableFrom(x)); foreach (var m in singletons) { foreach (var i in m.GetInterfaces()) { if (i.IsGenericType) { services.AddSingleton(i.MakeGenericType(), m.MakeGenericType()); } else { services.AddSingleton(i, m); } } } services.AddMailKit(optionBuilder => { var opts = new MailKitOptions() { Server = configuration["EmailSetting:Server"], Port = Convert.ToInt32(configuration["EmailSetting:Port"]), SenderName = configuration["EmailSetting:SenderName"], SenderEmail = configuration["EmailSetting:SenderEmail"], // enable ssl or tls Security = Convert.ToBoolean(configuration["EmailSetting:Security"]) }; if (Convert.ToBoolean(configuration["EmailSetting:NeedCredentials"])) { opts.Account = configuration["EmailSetting:Account"]; opts.Password = configuration["EmailSetting:Password"]; } optionBuilder.UseMailKit(opts); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddDbContext <ApplicationDbContext>(options => options.UseSqlite( Configuration.GetConnectionString("DefaultConnection"))); services.AddDefaultIdentity <IdentityUser>(options => { options.SignIn.RequireConfirmedEmail = true; }) // .AddDefaultUI(UIFramework.Bootstrap4) .AddEntityFrameworkStores <ApplicationDbContext>(); // ****************************************************************************************************************************** // to enable API to process token for authorization // ****************************************************************************************************************************** services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.SaveToken = true; options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuer = true, ValidateAudience = true, ValidAudience = "http://halo.world.com", ValidIssuer = "http://halo.world.com", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("MySuperSecretKey")) }; }); services.AddControllersWithViews(); services.AddRazorPages(); var mailKitOptions = Configuration.GetSection("Email").Get <MailKitOptions>(); services.AddMailKit(config => { var options = new MailKitOptions(); config.UseMailKit(mailKitOptions); }); }
private static IServiceCollection AddServices(this IServiceCollection services, IConfiguration configuration) { var mailKitOptions = new MailKitOptions() { Server = configuration["SmtpConfig:Server"], Port = Convert.ToInt32(configuration["SmtpConfig:Port"]), SenderName = configuration["SmtpConfig:SenderName"], SenderEmail = configuration["SmtpConfig:SenderEmail"], Account = configuration["SmtpConfig:Account"], Password = configuration["SmtpConfig:Password"], Security = true }; return(services .AddMailKit(optBuilder => optBuilder .UseMailKit(mailKitOptions))); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { //Entity Framework Part //to inject AppDbContext on the whole application to initialize database on the memory services.AddDbContext <AppDbContext>(config => { config.UseInMemoryDatabase("Memory"); }); //Identity bridge Part(used to generate repositories that is collection of abstraction methods) //AddDefaultTokenProviders: used to generate Token provider to generate Tokens for reset passwords //AddEntityFrameworkStores: used to link the Identity layer with database to communicate //AddIdentity : registers the services services.AddIdentity <IdentityUser, IdentityRole>(config => { config.Password.RequiredLength = 4; config.Password.RequireDigit = false; config.Password.RequireNonAlphanumeric = false; config.Password.RequireUppercase = false; //it will prevent register the user until confirm email config.SignIn.RequireConfirmedEmail = true; }) .AddEntityFrameworkStores <AppDbContext>() .AddDefaultTokenProviders(); services.ConfigureApplicationCookie(options => { options.AccessDeniedPath = "/Home/AccessDenied"; options.Cookie.Name = "IdentityCookie"; options.Cookie.HttpOnly = true; options.ExpireTimeSpan = new TimeSpan(0, 15, 0); options.LoginPath = "/Account/Login"; options.ReturnUrlParameter = "RedirectUrl"; options.LogoutPath = "/Account/Logout"; }); services.AddMailKit(config => { var options = new MailKitOptions(); config.UseMailKit(_config.GetSection("Email").Get <MailKitOptions>()); }); //to apply controllers with views services.AddControllersWithViews(); }
public void ConfigureServices(IServiceCollection services) { services.AddDbContext <AppDbContext>(config => { config.UseInMemoryDatabase("InMemoryDatabase"); }); services.AddIdentity <IdentityUser, IdentityRole>(config => { config.Password.RequiredLength = 4; config.Password.RequireDigit = false; config.Password.RequireNonAlphanumeric = false; config.Password.RequireUppercase = false; config.SignIn.RequireConfirmedEmail = true; }) .AddEntityFrameworkStores <AppDbContext>() .AddDefaultTokenProviders(); services.ConfigureApplicationCookie(config => { config.Cookie.Name = "Identity.Cookie"; config.LoginPath = "/Home/Login"; }); //var mailKitOptions = Configuration.GetSection("Email").Get<MailKitOptions>(); services.AddMailKit(config => { var options = new MailKitOptions { Server = string.Empty, Port = 0, Account = string.Empty, Password = string.Empty, SenderName = "Some Name here", SenderEmail = "*****@*****.**" }; config.UseMailKit(options); }); services.AddControllersWithViews(); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddDbContext <AppDbContext>(config => { config.UseInMemoryDatabase("Memory"); }); // AddIdentity Registers services services.AddIdentity <IdentityUser, IdentityRole>(config => { // Set Password Requirements config.Password.RequireDigit = false; config.Password.RequiredLength = 4; config.Password.RequireLowercase = false; config.Password.RequireNonAlphanumeric = false; config.Password.RequireUppercase = false; config.SignIn.RequireConfirmedEmail = true; }) .AddEntityFrameworkStores <AppDbContext>() .AddDefaultTokenProviders(); // Set up Login-Redirect (see also below) services.ConfigureApplicationCookie(config => { config.Cookie.Name = "Identity.Cookie"; config.LoginPath = "/Home/Login"; }); // For sending Verification-Emails // Get MailKitOptions from AppSettings MailKitOptions mailKitOptions = _config.GetSection("Email").Get <MailKitOptions>(); // Add MailKit services.AddMailKit(config => config.UseMailKit(mailKitOptions)); services.AddControllersWithViews(); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { if (!this._env.IsDevelopment()) { services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo("/keys/")); services.AddAntiforgery(options => { options.HeaderName = "X-XSRF-TOKEN"; }); } services.AddLogging(config => { config.AddConfiguration(this._configuration); config.AddConsole(); }); var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name; // configure proxy stuff if (this._configuration.GetValue("Proxy", false)) { services.Configure <ForwardedHeadersOptions>(options => { options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; options.RequireHeaderSymmetry = false; }); } // configure smtp services.AddMailKit(optionsBuilder => { var options = new MailKitOptions(); this._configuration.GetSection("Mail").Bind(options); optionsBuilder.UseMailKit(options); }); // configure render service for html mails services.AddScoped <IViewRenderService, ViewRenderService>(); services.Configure <CookiePolicyOptions>(options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddCors(); services.AddMvc(options => { if (!this._env.IsDevelopment()) { options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()); } }) .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddVcpShLdap(this._configuration, builder => builder.UseMySql(this._configuration.GetConnectionString("ChangeTracking"), sql => sql.MigrationsAssembly(migrationsAssembly))); services.AddVcpShIdentity(); var identityServerBuilder = services.AddIdentityServer(o => { o.UserInteraction.LoginUrl = "/login"; o.UserInteraction.LogoutUrl = "/logout"; o.IssuerUri = this._configuration.GetValue <string>("IssuerUrl"); o.PublicOrigin = o.IssuerUri; }) .AddAspNetIdentity <LdapUser>() .AddConfigurationStore(options => { options.ConfigureDbContext = builder => { builder.UseMySql(this._configuration.GetConnectionString("IdentityConfig"), sql => sql.MigrationsAssembly(migrationsAssembly)); }; }) .AddOperationalStore(options => { options.EnableTokenCleanup = true; options.TokenCleanupInterval = 3600; options.ConfigureDbContext = builder => { builder.UseMySql(this._configuration.GetConnectionString("IdentityOperational"), sql => sql.MigrationsAssembly(migrationsAssembly)); }; }) .AddProfileService <ProfileManager>(); // configure jwt secret services.AddSingleton( new SigningCredentials( new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this._configuration.GetValue <string>("JwtSecret"))), SecurityAlgorithms.HmacSha256)); // configure identity server signing credential if (this._configuration.GetValue <string>("SigningCredential").IsNullOrEmpty()) { identityServerBuilder.AddDeveloperSigningCredential(); } else { var cert = new X509Certificate2( this._configuration.GetValue <string>("SigningCredential"), this._configuration.GetValue <string>("SigningCredentialPassword")); identityServerBuilder.AddSigningCredential(cert); } }
/// <summary> /// add email service to di /// </summary> /// <param name="options"></param> /// <param name="lifetime"></param> /// <returns></returns> public IMailKitOptionsBuilder UseMailKit(MailKitOptions options, ServiceLifetime lifetime = ServiceLifetime.Scoped) { AddProviderService(options); serviceCollection.TryAdd(new ServiceDescriptor(typeof(IEmailService), typeof(EmailService), lifetime)); return(this); }
private void AddProviderService(MailKitOptions options) { MailKitProvider provider = new MailKitProvider(options); serviceCollection.TryAddSingleton <IMailKitProvider>(provider); }
public MessagesService(MailKitOptions options, ILogger <MessagesService> logger) { _options = options; _logger = logger; }
public MessagesService(MailKitOptions options) { _options = options; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { if (!this._env.IsDevelopment()) { services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo("/keys/")); } services.AddLogging(config => { config.AddConfiguration(this._configuration); config.AddConsole(); }); var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name; services.AddVcpShLdap(this._configuration, builder => builder.UseMySql(this._configuration.GetConnectionString("ChangeTracking"), sql => sql.MigrationsAssembly(migrationsAssembly))); services.AddVcpShIdentity(); services.AddVcpShGroupAdministrationDal(); // configure proxy stuff if (this._configuration.GetValue("Proxy", false)) { services.Configure <ForwardedHeadersOptions>(options => { options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; options.RequireHeaderSymmetry = false; }); } // configure smtp services.AddMailKit(optionsBuilder => { var options = new MailKitOptions(); this._configuration.GetSection("Mail").Bind(options); optionsBuilder.UseMailKit(options); }); services.AddAuthentication(o => { o.DefaultScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme; o.DefaultAuthenticateScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme; }).AddIdentityServerAuthentication(options => { this._configuration.GetSection("Authentication").Bind(options); }); // additional configuration services.AddMvc(options => { // if (!this._env.IsDevelopment()) { // options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()); // } // options.AddMetricsResourceFilter() }) .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddCors(options => { options.AddPolicy("sso-backend", policy => { policy .WithOrigins(this._configuration.GetSection("Authentication")["Authority"]) .AllowAnyHeader() .AllowAnyMethod(); }); }); // if (!this._env.IsDevelopment()) { // services.AddAntiforgery(options => // { // options.HeaderName = "X-XSRF-TOKEN"; // }); // } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext <hhDbContext>(opts => { opts.EnableDetailedErrors(); opts.UseNpgsql(Configuration.GetConnectionString("dbConnection.dev")); }); services.AddIdentity <User, Role>(options => { options.SignIn.RequireConfirmedEmail = true; }) .AddEntityFrameworkStores <hhDbContext>() .AddSignInManager <SignInManager <User> >() .AddDefaultTokenProviders(); var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:TokenKey"])); // TokenKey stored in appsettings.development.json for development. Will need to be stored on server in Production. services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(opt => { opt.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = key, ValidateAudience = false, ValidateIssuer = false, ValidateLifetime = true, ClockSkew = TimeSpan.Zero }; }); services.AddCors(opt => { opt.AddPolicy("CorsPolicy", policy => { policy.AllowAnyHeader() .AllowAnyMethod() .WithExposedHeaders("WWW-Authenticate") .WithOrigins("https://localhost:5001") .AllowCredentials(); }); }); services.AddMediatR(typeof(List.Handler).Assembly); var mailKitOptions = Configuration.GetSection("SmtpEthereal").Get <MailKitOptions>(); services.AddMailKit(config => { var options = new MailKitOptions(); config.UseMailKit(mailKitOptions); }); services.AddControllers(opt => { var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build(); opt.Filters.Add(new AuthorizeFilter(policy)); }) .AddFluentValidation(config => { config.RegisterValidatorsFromAssemblyContaining <List>(); }); services.AddScoped <ITrailsService, TrailsService>(); services.AddScoped <IUserAccessor, UserAccessor>(); services.AddScoped <IEntity, BaseEntity>(); services.AddScoped(typeof(IRepository <>), typeof(Repository <>)); services.AddScoped <ITokenGenerator, TokenGenerator>(); services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" }); options.CustomSchemaIds(x => x.FullName); // To Enable authorization using Swagger (JWT) options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme() { Name = "Authorization", Type = SecuritySchemeType.Http, Scheme = "Bearer", BearerFormat = "JWT", In = ParameterLocation.Header, Description = "JWT Authorization header using the Bearer scheme.", }); options.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }, new string[] {} } }); }); }
public InvitationGeneratedHandler(IMailService mailService, IOptions <MailKitOptions> options) { _mailService = mailService; _options = options.Value; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext <PikeSafetyDbContext>(options => { options.UseMySQL(Configuration.GetConnectionString("PikeSafetyDB")) .EnableSensitiveDataLogging() .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking) ; }); var builder = services.AddIdentityCore <AppUser>(options => { options.SignIn.RequireConfirmedEmail = true; }); var identityBuilder = new IdentityBuilder(builder.UserType, builder.Services); identityBuilder.AddRoles <AppRole>(); identityBuilder.AddEntityFrameworkStores <PikeSafetyDbContext>(); identityBuilder.AddSignInManager <SignInManager <AppUser> >(); identityBuilder.AddDefaultTokenProviders(); var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:TokenKey"])); // TokenKey stored in appsettings.json for development. Will need to be stored on server in Production. services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(opt => { opt.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = key, ValidateAudience = false, ValidateIssuer = false, ValidateLifetime = true, ClockSkew = TimeSpan.Zero }; }); services.AddCors(opt => { opt.AddPolicy("CorsPolicy", policy => { policy.AllowAnyHeader() .AllowAnyMethod() .WithExposedHeaders("WWW-Authenticate") .WithOrigins("https://localhost:5001") .AllowCredentials(); }); }); services.AddMediatR(typeof(Login.Handler).Assembly); services.AddAutoMapper(typeof(Login.Handler)); var mailKitOptions = Configuration.GetSection("SmtpEthereal").Get <MailKitOptions>(); services.AddMailKit(config => { var options = new MailKitOptions(); config.UseMailKit(mailKitOptions); }); services.AddControllers(opt => { var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build(); opt.Filters.Add(new AuthorizeFilter(policy)); }).AddFluentValidation(config => { config.RegisterValidatorsFromAssemblyContaining <Login>(); }); services.AddScoped <IEntityBase, EntityBase>(); services.AddScoped(typeof(IGenericRepository <>), typeof(GenericRepository <>)); services.AddScoped <ITokenGenerator, TokenGenerator>(); services.AddScoped <IUserAccessor, UserAccessor>(); services.AddScoped <IRoleAccessor, RoleAccessor>(); services.AddScoped <IUserService, UserService>(); services.AddScoped <ICompanyService, CompanyService>(); services.AddScoped <ISiteService, SiteService>(); services.AddScoped <IModelConverters, ModelConverters>(); services.AddScoped <IReportService, ReportService>(); // In production, the React files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/build"; }); IdentityModelEventSource.ShowPII = true; }
public static IMailKitOptionsBuilder UseMailKit(IMailKitOptionsBuilder builder, MailKitOptions options, ServiceLifetime lifetime = ServiceLifetime.Scoped) { Check.Argument.IsNotNull(builder, nameof(builder), "The MailKitOptionsBuilder is null"); Check.Argument.IsNotNull(options, nameof(options), "The MailKitOptions is null"); return(builder.UseMailKit(options, lifetime)); }
public void AutoSendMail() { string account = _configService.GetSysParamValue(FapPlatformConstants.MailAccount); string password = _configService.GetSysParamValue(FapPlatformConstants.MailPassword); string server = _configService.GetSysParamValue(FapPlatformConstants.MailServer); int? port = _configService.GetSysParamValue(FapPlatformConstants.MailPort).ToInt(); string accountName = _configService.GetSysParamValue(FapPlatformConstants.MailAccountName); MailKitOptions mailOption = new MailKitOptions() { Account = account, Password = password, Port = (int)port, Server = server, SenderEmail = account, SenderName = accountName }; IEmailService service = new EmailService(new MailKitProvider(mailOption)); try { SendEmail(); } catch (Exception ex) { _logger.LogError($"任务调度 邮件发送异常信息:{ex.Message}"); } void SendEmail() { //未发送或发送次数小于5,注:可能发送失败,每次发送次数会增加 IEnumerable <FapMail> listMails = _dataAccessor.Query <FapMail>($"select * from FapMail where SendStatus=0 and SendCount<5"); if (listMails == null || listMails.Count() < 1) { _logger.LogInformation("无邮件可发"); return; } //招聘相关的特殊处理 var rcrtMails = listMails.Where <FapMail>(m => m.MailCategory == "招聘相关"); IEnumerable <dynamic> rcrtEmailAddress = new List <dynamic>(); if (rcrtMails != null && rcrtMails.Count() > 0) { rcrtEmailAddress = _dataAccessor.Query("select * from RcrtMail where Enabled=1"); } foreach (FapMail mail in listMails) { if (mail.RecipientEmailAddress.IsMissing()) { mail.SendCount = 5; mail.Failures = "收件人为空"; _dataAccessor.Update <FapMail>(mail); continue; } //预计发送时间 if (mail.PreSendTime.IsPresent()) { DateTime pre = Convert.ToDateTime(mail.PreSendTime); //不到预计时间不发送 if (pre > DateTime.Now) { continue; } } List <AttachmentInfo> listAtts = new List <AttachmentInfo>(); var attachemts = _fileService.FileList(mail.Attachment); if (attachemts != null && attachemts.Any()) { foreach (var att in attachemts) { listAtts.Add(new AttachmentInfo { ContentType = att.FileType, UniqueId = att.Id.ToString(), FileName = att.FileName, Stream = _fileService.GetFileStream(att) }); } } string[] arryRec = mail.RecipientEmailAddress.Split(';'); string failMsg = string.Empty; //是否分别发送,分别发送的情况下 就没有抄送和密送 if (mail.IsSeparate == 1) { if (arryRec != null && arryRec.Length > 0) { foreach (string rec in arryRec) { string emailAddr = rec.Trim(); if (emailAddr.IsPresent()) { try { //招聘的特殊处理 if (mail.MailCategory == "招聘相关" && mail.SenderEmailAddress.IsPresent()) { var rcrtMail = rcrtEmailAddress.FirstOrDefault(m => m.Account == mail.SenderEmailAddress); if (rcrtMail != null) { try { MailKitOptions rcrtMailOption = new MailKitOptions() { Account = rcrtMail.Account, Password = rcrtMail.Password, Port = Convert.ToInt32(rcrtMail.SmtpPort), Server = rcrtMail.Smtp, SenderEmail = rcrtMail.Account, SenderName = "招聘负责人" }; IEmailService mailService = new EmailService(new MailKitProvider(rcrtMailOption)); mailService.Send(emailAddr, mail.Subject, mail.MailContent, MimeKit.Text.TextFormat.Html, listAtts); } catch (Exception ex) { failMsg += $"{ex.Message}"; _logger.LogError($"招聘相关 邮件发送失败:{ex.Message}"); } _logger.LogInformation("招聘相关 任务调度,定时执行 发送邮件 成功=====>" + mail.Fid); } } else { try { service.Send(emailAddr, mail.Subject, mail.MailContent, MimeKit.Text.TextFormat.Html, listAtts); } catch (Exception ex) { failMsg += $"{ex.Message}"; _logger.LogError($"邮件发送失败:{ex.Message}"); } _logger.LogInformation("任务调度,定时执行 发送邮件 成功=====>" + mail.Fid); } } catch (Exception ex) { _logger.LogError($"分割发送邮件异常,邮件地址:{rec + ex.Message}"); continue; } } } } } else { if (mail.MailCategory == "招聘相关" && mail.SenderEmailAddress.IsPresent()) { var rcrtMail = rcrtEmailAddress.FirstOrDefault(m => m.Account == mail.SenderEmailAddress); if (rcrtMail != null) { try { MailKitOptions rcrtMailOption = new MailKitOptions() { Account = rcrtMail.Account, Password = rcrtMail.Password, Port = Convert.ToInt32(rcrtMail.SmtpPort), Server = rcrtMail.Smtp, SenderEmail = rcrtMail.Account, SenderName = "招聘负责人" }; IEmailService mailService = new EmailService(new MailKitProvider(rcrtMailOption)); mailService.Send(mail.RecipientEmailAddress, mail.CCEmailAddress, mail.BCCEmailAddress, mail.Subject, mail.MailContent, TextFormat.Html, listAtts); } catch (Exception ex) { failMsg += $"{ex.Message}"; _logger.LogError($"招聘相关 合并发送邮件发送失败:{ex.Message}"); } _logger.LogInformation("招聘相关 任务调度,定时执行 发送邮件 成功=====>" + mail.Fid); } else { try { service.Send(mail.RecipientEmailAddress, mail.CCEmailAddress, mail.BCCEmailAddress, mail.Subject, mail.MailContent, TextFormat.Html, listAtts); } catch (Exception ex) { failMsg += $"{ex.Message}"; _logger.LogError($"招聘相关 合并发送邮件发送失败:{ex.Message}"); } _logger.LogInformation("招聘相关 任务调度,定时执行 发送邮件 成功=====>" + mail.Fid); } } else { try { service.Send(mail.RecipientEmailAddress, mail.CCEmailAddress, mail.BCCEmailAddress, mail.Subject, mail.MailContent, TextFormat.Html, listAtts); } catch (Exception ex) { failMsg += $"{ex.Message}"; _logger.LogError($" 合并发送邮件发送失败:{ex.Message}"); } _logger.LogInformation(" 任务调度,定时执行 发送邮件 成功=====>" + mail.Fid); } } if (failMsg.IsPresent()) { mail.SendCount += 1; mail.SendStatus = 1; mail.Failures = failMsg; _dataAccessor.Update <FapMail>(mail); } else { mail.SendStatus = 1; mail.SendCount += 1; _dataAccessor.Update <FapMail>(mail); } } } }
public MailKitEmailSender(IOptions <MailKitOptions> optionsAccessor) { _mailKitOptions = optionsAccessor.Value; }
public MailKitProvider(MailKitOptions mailKitOptions) { Options = mailKitOptions; }
/// <summary> /// 接收简历 /// </summary> public async void ReceiveResume(IEnumerable <RcrtMail> mails) { foreach (var mail in mails) { await ReceiveFromMailBox(mail.Pop3Server, mail.Pop3Port, mail.Account, mail.Password, mail.UseSSL == 1?true : false, MailProtocolEnum.Pop3).ConfigureAwait(false); } async Task ReceiveFromMailBox(string host, int port, string account, string pwd, bool useSSL, MailProtocolEnum protocol) { DynamicParameters param = new DynamicParameters(); param.Add("EmpUid", _applicationContext.EmpUid); var seenUids = _dbContext.QueryWhere <RcrtMailReadRecord>("EmpUid=@EmpUid", param).Select(s => s.MessageUid); MailKitOptions moptions = new MailKitOptions() { Server = host, Port = port, Account = account, Password = pwd, Security = useSSL, SenderEmail = account, SenderName = account }; IEmailService mailService = new EmailService(new MailKitProvider(moptions)); if (protocol == MailProtocolEnum.Pop3) { List <MimeMessage> mimeMsg = await mailService.RecieveEmailByPop3Async(seenUids).ConfigureAwait(false); if (mimeMsg.Any()) { var newUids = mimeMsg.Select(m => m.MessageId).ToList(); AddResumeByMail(mimeMsg); AddReadRecord(newUids); } } else if (protocol == MailProtocolEnum.Imap) { //默认收取前一天至今 List <MimeMessage> mimeMsg = await mailService.RecieveEmailByImapAsync(seenUids).ConfigureAwait(false); if (mimeMsg.Any()) { var newUids = mimeMsg.Select(m => m.MessageId).ToList(); AddResumeByMail(mimeMsg); AddReadRecord(newUids); } } } void AddReadRecord(IEnumerable <string> newUids) { List <RcrtMailReadRecord> list = new List <RcrtMailReadRecord>(); foreach (var uid in newUids) { RcrtMailReadRecord model = new RcrtMailReadRecord(); model.EmpUid = _applicationContext.EmpUid; model.MessageUid = uid; list.Add(model); } if (list.Any()) { _dbContext.InsertBatchSql(list); } } void AddResumeByMail(IEnumerable <MimeMessage> messages) { var list = _dbContext.QueryAll <RcrtWebsite>(); List <IParseEmailService> parseMailServiceList = new List <IParseEmailService>(); foreach (var website in list) { if (website.EmailAnalysisPlugin.IsPresent()) { //解析插件 IParseEmailService analysis = ParseEmailService(website.EmailAnalysisPlugin); if (analysis != null) { parseMailServiceList.Add(analysis); } } } //获取黑名单 var blackList = _dbContext.Query <RcrtResume>($"select {nameof(RcrtResume.Mobile)} from {nameof(RcrtResume)} where {nameof(RcrtResume.ResumeStatus)}='{RcrtResumeStatus.BlackList}'"); if (parseMailServiceList.Any()) { foreach (var message in messages) { foreach (var service in parseMailServiceList) { var result = service.Analysis(message, blackList); if (result) { break; } } } } } IParseEmailService ParseEmailService(string parseEmailServiceClass) { IParseEmailService dataInterceptor = null; if (parseEmailServiceClass.IsPresent()) { //此处不能缓存,容易使session丢失,若要缓存的话需要重新赋值session try { Type type = Sys.Type.GetType(parseEmailServiceClass); if (type != null && type.GetInterface("IParseEmailService") != null) { //dataInterceptor = (IDataInterceptor)Activator.CreateInstance(type, new object[] { _serviceProvider, this }); dataInterceptor = (IParseEmailService)ActivatorUtilities.GetServiceOrCreateInstance(_serviceProvider, type); } } catch (Exception ex) { _logger.LogError(ex.Message); return(null); } } return(dataInterceptor); } }