Readdy Write  
0,00 €
Your View Money
Views: Count
Self 20% 0
Your Content 60% 0

Users by Links 0
u1*(Content+Views) 10% 0
Follow-Follower 0
s2*(Income) 5% 0

Count
Followers 0
Login Register as User

Email einrichten für Asp.Net Core mit React / Angular

18.02.2021 (👁8184)


 

Für die Aktivierung von Emails zur Registrierung im Asp.Net Core 5 Framework als Vorlage für SPA Angular und React, Vue.js Frontend Anwendungen mit dem Microsoft Identity Framework benötigt man die Dateien:

Services/EmailSender

Services/AuthMessageSenderOptions

Secrets.json :-> Anpassungen

Startup.cs     :-> Anpassungen

File Services/EmailSender.cs

using Microsoft.AspNetCore.Identity.UI.Services;

using Microsoft.Extensions.Options;

using System;

using System.Net;

using System.Net.Mail;

using System.Threading.Tasks;

namespace Demo_Identity_ReactAsp.Services

{

    public class EmailSender : IEmailSender

    {

      

        public EmailSender(IOptions<AuthMessageSenderOptions> optionsAccessor)

        {

            _sender_config = optionsAccessor.Value;

        }

        public AuthMessageSenderOptions _sender_config { get; } //set only via Secret Manager

        public  Task SendEmailAsync(string email, string subject, string message)

        {

            return  Execute(subject, message, email);

        }

        public  Task Execute( string subject, string message, string email_to)

        {

            //------------< SendEmailAsync() >------------

            //< check >

            if (email_to == null) return Task.FromException(null);  //todo <bool>=false

            //</ check >

            try

            {

                //-< SmtpServer_Client >-

                SmtpClient smtp = new SmtpClient();

                smtp.Host = _sender_config.Host;

                smtp.Port = _sender_config.intPort;

                smtp.Credentials = new NetworkCredential(_sender_config.Email_User, _sender_config.Email_Passwort);

                smtp.EnableSsl = false;

                //-</ SmtpServer_Client >-

                //-< setup Email >-

                MailMessage email_Message = new MailMessage();

                email_Message.To.Add(new MailAddress(email_to));

                email_Message.From = new MailAddress(_sender_config.Display_From_Email_Address, _sender_config.Display_From_Name);

                email_Message.Subject = subject;

                email_Message.Body = message;

                email_Message.IsBodyHtml = true;

                //email.Priority = MailPriority.High;

                //-</ setup Email >-

                //< send >

                return smtp.SendMailAsync(email_Message);

                //</ send >

            }

            catch (Exception ex)

            {

                //do something here

                Console.WriteLine("Error EmailSender.cs error:" + ex.InnerException);

                return Task.FromException(ex);

            }

            //return true;

            //------------</ SendEmailAsync() >------------

        }

    }

}

 

Startup.cs

 

Startup.cs

using Microsoft.AspNetCore.Authentication;

using Microsoft.AspNetCore.Builder;

using Microsoft.AspNetCore.Hosting;

using Microsoft.AspNetCore.Identity;

using Microsoft.AspNetCore.Identity.UI;

using Microsoft.AspNetCore.HttpsPolicy;

using Microsoft.AspNetCore.SpaServices.ReactDevelopmentServer;

using Microsoft.EntityFrameworkCore;

using Demo_Identity_ReactAsp.Data;

using Demo_Identity_ReactAsp.Models;

using Microsoft.Extensions.Configuration;

using Microsoft.Extensions.DependencyInjection;

using Microsoft.Extensions.Hosting;

using Microsoft.AspNetCore.Identity.UI.Services;

using Demo_Identity_ReactAsp.Services;

namespace Demo_Identity_ReactAsp

{

    public class Startup

    {

        public Startup(IConfiguration configuration)

        {

            Configuration = configuration;

        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.

        public void ConfigureServices(IServiceCollection services)

        {

            services.AddDbContext<ApplicationDbContext>(options =>

                options.UseSqlite(

                    Configuration.GetConnectionString("DefaultConnection")));

            services.AddDatabaseDeveloperPageExceptionFilter();

            services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)

                .AddEntityFrameworkStores<ApplicationDbContext>();

            services.AddIdentityServer()

                .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

            services.AddAuthentication()

                .AddIdentityServerJwt();

            services.AddControllersWithViews();

            //-< Email Registration >

            services.AddTransient<IEmailSender, EmailSender>();        

            services.Configure<AuthMessageSenderOptions>(Configuration);

            //-</ Email Registration >

            services.AddRazorPages();

            // In production, the React files will be served from this directory

            services.AddSpaStaticFiles(configuration =>

            {

                configuration.RootPath = "ClientApp/build";

            });

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

        {

            if (env.IsDevelopment())

            {

                app.UseDeveloperExceptionPage();

                app.UseMigrationsEndPoint();

            }

            else

            {

                app.UseExceptionHandler("/Error");

                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.

                app.UseHsts();

            }

            app.UseHttpsRedirection();

            app.UseStaticFiles();

            app.UseSpaStaticFiles();

            app.UseRouting();

            app.UseAuthentication();

            app.UseIdentityServer();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>

            {

                endpoints.MapControllerRoute(

                    name: "default",

                    pattern: "{controller}/{action=Index}/{id?}");

                endpoints.MapRazorPages();

            });

            app.UseSpa(spa =>

            {

                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())

                {

                    spa.UseReactDevelopmentServer(npmScript: "start");

                }

            });

        }

    }

}

 

 

 

EmailSender ruft die internen Werte des Providers auf

namespace Demo_Identity_ReactAsp.Services

{

    public class AuthMessageSenderOptions

    {

        //*values by secretsmanager

        //< init >

        public string Host { get; set; }

        public int intPort { get; set; }

        public string Email_User{ get; set; }

        public string Email_Passwort { get; set; }

        public string Display_From_Email_Address { get; set; }

        public string Display_From_Name { get; set; }

        //</ init >

    }

}

 

 

 

 

In den Projekt Secrets müssen die gleichen Variablen stehen

Secrets.json

{

  "Display_From_Email_Address": "postmaster@myDomain.de",

  "Display_From_Name": "Postmaster myDomain.de",

  "Host": "mail.myDomain.de",

  "intPort": 25,

  "Email_User": "myUser@myDomain.de",

  "Email_Passwort": "myPassword"

}