Asp.Net Core: Eigenen Email Provider einbinden
Unter Asp.net core MVC muss man einen eigenen Email-Service einstellen, welcher die Emails versendet.
Hierzu benötigt man nur einen Email-Account und die Provider-Daten, und dann kann man den Email-Service einfach definieren.
Hierzu muss man einen Ordner Services anlegen
Und dann die Datei EmailSender.cs und IEmailSender.cs
Anschliessend muss man den Email-Service noch in der Startup.cs definieren und schon sollte der Email-Dienst funktionieren.
Services
IEmailSender.cs
using System.Threading.Tasks;
namespace Freelance.Services { public interface IEmailSender { Task SendEmailAsync(string email, string subject, string message); } } |
Datei
EmailSender.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net; //NetworkCredential using System.Net.Mail; //SmtpClient using System.Threading.Tasks;
namespace Freelance.Services { // This class is used by the application to send email for account confirmation and password reset. public class EmailSender : IEmailSender { public async Task SendEmailAsync(string To_Email_Address, string subject, string message) { //------------< SendEmailAsync() >------------ //< check > if (To_Email_Address == null) return; //todo <bool>=false //</ check >
try { //< init > //*From Globals string sFrom_Email_Address = Website_Constants.Mail_From_Email_Address; string sFrom_Email_DisplayName = Website_Constants.Mail_From_Email_DisplayName; string sHost = Website_Constants.Mail_Host; string intPort = Website_Constants.Mail_Port; string sEmail_Login = Website_Constants.Mail_Email_Login ; string sEmail_Passwort = Website_Constants.Mail_Email_Passwort; //</ init >
//-< setup Email >- MailMessage email = new MailMessage(); email.To.Add(new MailAddress(To_Email_Address)); email.From=new MailAddress(sFrom_Email_Address,sFrom_Email_DisplayName); email.Subject = subject; email.Body = message; email.IsBodyHtml = true; //email.Priority = MailPriority.High; //-</ setup Email >-
//-< EmailClient >- SmtpClient smtp = new SmtpClient(); smtp.Host = sHost; smtp.Port = Convert.ToInt32(intPort); smtp.Credentials = new NetworkCredential(sEmail_Login, sEmail_Passwort); smtp.EnableSsl = false; //-</ EmailClient >-
//< send > await smtp.SendMailAsync(email); //</ send > }
catch (Exception ex) { //do something here Console.WriteLine("Error EmailSender.cs error:" + ex.Message); }
//return true; //------------</ SendEmailAsync() >------------ } } } |
startup.cs
in Startup muss man den Service in ConfigureServices einbinden
public void ConfigureServices(IServiceCollection services) { //-----------< ConfigureServices() >----------- services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Website_Constants.Connectionstring));
//--< Facebook Api >--
//--< Identity >-- services.AddIdentity<ApplicationUser, IdentityRole>(config => { //< send Register Email > //*prevents registered users from logging in until their email is confirmed. config.SignIn.RequireConfirmedEmail = true; //</ send Register Email > }) .. |
Und
.. // Add application services. services.AddTransient<IEmailSender, EmailSender>();
var optRewrite = new RewriteOptions() .AddRedirectToHttpsPermanent();
services.AddMvc();
//-----------</ ConfigureServices() >----------- }
|
Anwendung: Account
Die erste Anwendung findet in dem Account-Controller von Microsoft ein.
Wenn man das Passwort vergessen hat, dann soll eine Email zugesandt werden.
[HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null) { //------------< Register_Postback() >------------ ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { //< new User > var aspNetUser = new ApplicationUser { UserName = model.Username, Email = model.Email }; string IDAspNetUser = aspNetUser.Id; //</ new User >
//< create > var result = await _userManager.CreateAsync(aspNetUser, model.Password); //</ create > if (result.Succeeded) { //----< User Created Successfull >---- _logger.LogInformation("User created a new account with password.");
//< confirm > var code = await _userManager.GenerateEmailConfirmationTokenAsync(aspNetUser); var callbackUrl = Url.EmailConfirmationLink(aspNetUser.Id, code, Request.Scheme); await _emailSender.SendEmailConfirmationAsync(model.Email, callbackUrl); //</ confirm >
//< get_Info > UserModel user = _dbContext.tbl_Users.SingleOrDefault(i => i.IDAspNetUser == IDAspNetUser); if (user == null) { //< add > user = new UserModel(); user.IDAspNetUser = IDAspNetUser; user.dtCreated = DateTime.Now; _dbContext.tbl_Users.Add(user); //</ add >
//< save > try { await _dbContext.SaveChangesAsync(true); } catch (DbUpdateConcurrencyException) { return Content("Update Error User_info"); } //< save > }
long IDCurrent_User = user.IDUser;
//< login > //*logs in automatically. eventually disable await _signInManager.SignInAsync(aspNetUser, isPersistent: false); //</ login > _logger.LogInformation("User created a new account with password.");
return RedirectToLocal(returnUrl); //----</ User Created Successfull >---- } AddErrors(result); }
//< failed > //* If we got this far, something failed, redisplay form return View(model); //</ failed > //------------</ Register_Postback() >------------ } |
[HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model) { //----------------< ForgotPassword_postback() >---------------- //*on enter a email and push button to reset password
if (ModelState.IsValid) { //----< DataModel ok >---- var user = await _userManager.FindByEmailAsync(model.Email); if (user == null) //*Project:ms-original Code did only send when not confirmed.. so no second time || !(await _userManager.IsEmailConfirmedAsync(user)) { //-< error: user not found >- // Don't reveal that the user does not exist or is not confirmed return RedirectToAction(nameof(ForgotPasswordConfirmation)); //-</ error: user not found >- }
// For more information on how to enable account confirmation and password reset please // visit https://go.microsoft.com/fwlink/?LinkID=532713 var code = await _userManager.GeneratePasswordResetTokenAsync(user); var callbackUrl = Url.ResetPasswordCallbackLink(user.Id, code, Request.Scheme);
//< send email > await _emailSender.SendEmailAsync(model.Email, "Reset Password",$"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>"); //</ send email >
//< view > return RedirectToAction(nameof(ForgotPasswordConfirmation)); //</ view > //----</ DataModel ok >---- }
// If we got this far, something failed, redisplay form return View(model);
//----------------</ ForgotPassword_postback() >---------------- } |