Projekt-Anfragen: Tel: 07022/9319004 info@CodeDocu.de Software Entwicklung in C# WPF Asp.Net Core Vba Excel Word SQL-Server EF Linq, UWP Net
#

 
 
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

 

 

usingSystem.Threading.Tasks;

 

namespaceFreelance.Services

{

publicinterfaceIEmailSender

{

TaskSendEmailAsync(stringemail,stringsubject,stringmessage);

}

}
 


 
Datei
EmailSender.cs
 

usingSystem;

usingSystem.Collections.Generic;

usingSystem.Linq;

usingSystem.Net;//NetworkCredential

usingSystem.Net.Mail;//SmtpClient

usingSystem.Threading.Tasks;

 

namespaceFreelance.Services

{

//Thisclassisusedbytheapplicationtosendemailforaccountconfirmationandpasswordreset.

publicclassEmailSender:IEmailSender

{

publicasyncTaskSendEmailAsync(stringTo_Email_Address,stringsubject,stringmessage)

{

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

//<check>

if(To_Email_Address==null)return;//todo<bool>=false

//</check>

 

try

{

//<init>

//*FromGlobals

stringsFrom_Email_Address=Website_Constants.Mail_From_Email_Address;

stringsFrom_Email_DisplayName=Website_Constants.Mail_From_Email_DisplayName;

stringsHost=Website_Constants.Mail_Host;

stringintPort=Website_Constants.Mail_Port;

stringsEmail_Login=Website_Constants.Mail_Email_Login;

stringsEmail_Passwort=Website_Constants.Mail_Email_Passwort;

//</init>

 

//-<setupEmail>-

MailMessageemail=newMailMessage();

email.To.Add(newMailAddress(To_Email_Address));

email.From=newMailAddress(sFrom_Email_Address,sFrom_Email_DisplayName);

email.Subject=subject;

email.Body=message;

email.IsBodyHtml=true;

//email.Priority=MailPriority.High;

//-</setupEmail>-

 

//-<EmailClient>-

SmtpClientsmtp=newSmtpClient();

smtp.Host=sHost;

smtp.Port=Convert.ToInt32(intPort);

smtp.Credentials=newNetworkCredential(sEmail_Login,sEmail_Passwort);

smtp.EnableSsl=false;

//-</EmailClient>-

 

//<send>

awaitsmtp.SendMailAsync(email);

//</send>

}

 

catch(Exceptionex)

{

//dosomethinghere

Console.WriteLine("ErrorEmailSender.cserror:"+ex.Message);

}

 

 

//returntrue;

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

}

}

}
 


 
 
startup.cs
in Startup muss man den Service in ConfigureServices einbinden

publicvoidConfigureServices(IServiceCollectionservices)

{

//-----------<ConfigureServices()>-----------

services.AddDbContext<ApplicationDbContext>(options=>options.UseSqlServer(Website_Constants.Connectionstring));

 

//--<FacebookApi>--

 

//--<Identity>--

services.AddIdentity<ApplicationUser,IdentityRole>(config=>

{

//<sendRegisterEmail>

//*preventsregisteredusersfromlogginginuntiltheiremailisconfirmed.

config.SignIn.RequireConfirmedEmail=true;

//</sendRegisterEmail>

})
..


 
Und

..

//Addapplicationservices.

services.AddTransient<IEmailSender,EmailSender>();

 

varoptRewrite=newRewriteOptions()

.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]
publicasyncTask<IActionResult>ForgotPassword(ForgotPasswordViewModelmodel)
{
//----------------<ForgotPassword_postback()>----------------
//*onenteraemailandpushbuttontoresetpassword
 
if(ModelState.IsValid)
{
//----<DataModelok>----
varuser=await_userManager.FindByEmailAsync(model.Email);
if(user==null)//*Project:ms-originalCodedidonlysendwhennotconfirmed..sonosecondtime||!(await_userManager.IsEmailConfirmedAsync(user))
{
//-<error:usernotfound>-
//Don'trevealthattheuserdoesnotexistorisnotconfirmed
returnRedirectToAction(nameof(ForgotPasswordConfirmation));
//-</error:usernotfound>-
}
 
//Formoreinformationonhowtoenableaccountconfirmationandpasswordresetplease
//visithttps://go.microsoft.com/fwlink/?LinkID=532713
varcode=await_userManager.GeneratePasswordResetTokenAsync(user);
varcallbackUrl=Url.ResetPasswordCallbackLink(user.Id,code,Request.Scheme);
 

            
//<sendemail>
await_emailSender.SendEmailAsync(model.Email,"ResetPassword",$"Pleaseresetyourpasswordbyclickinghere:<ahref='{callbackUrl}'>link</a>");
//</sendemail>
 
//<view>
returnRedirectToAction(nameof(ForgotPasswordConfirmation));
//</view>
//----</DataModelok>----
}
 
//Ifwegotthisfar,somethingfailed,redisplayform
returnView(model);
 
//----------------</ForgotPassword_postback()>----------------
}

 

 
 
Und beim Registrieren
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
publicasyncTask<IActionResult>Register(RegisterViewModelmodel,stringreturnUrl=null)
{
//------------<Register_Postback()>------------
ViewData["ReturnUrl"]=returnUrl;
if(ModelState.IsValid)
{
//<newUser>
varaspNetUser=newApplicationUser{UserName=model.Username,Email=model.Email};
stringIDAspNetUser=aspNetUser.Id;
//</newUser>
 
//<create>
varresult=await_userManager.CreateAsync(aspNetUser,model.Password);
//</create>
if(result.Succeeded)
{
//----<UserCreatedSuccessfull>----
_logger.LogInformation("Usercreatedanewaccountwithpassword.");
 
//<confirm>
varcode=await_userManager.GenerateEmailConfirmationTokenAsync(aspNetUser);
varcallbackUrl=Url.EmailConfirmationLink(aspNetUser.Id,code,Request.Scheme);
await_emailSender.SendEmailConfirmationAsync(model.Email,callbackUrl);
//</confirm>
 

            
//<get_Info>
UserModeluser=_dbContext.tbl_Users.SingleOrDefault(i=>i.IDAspNetUser==IDAspNetUser);
if(user==null)
{
//<add>
user=newUserModel();
user.IDAspNetUser=IDAspNetUser;
user.dtCreated=DateTime.Now;
_dbContext.tbl_Users.Add(user);
//</add>
 
//<save>
try
{
await_dbContext.SaveChangesAsync(true);
}
catch(DbUpdateConcurrencyException)
{
returnContent("UpdateErrorUser_info");
}
//<save>
}
 
longIDCurrent_User=user.IDUser;
 
//<login>
//*logsinautomatically.eventuallydisable
await_signInManager.SignInAsync(aspNetUser,isPersistent:false);
//</login>
_logger.LogInformation("Usercreatedanewaccountwithpassword.");
 

            

            
returnRedirectToLocal(returnUrl);
//----</UserCreatedSuccessfull>----
}
AddErrors(result);
}
 
//<failed>
//*Ifwegotthisfar,somethingfailed,redisplayform
returnView(model);
//</failed>
//------------</Register_Postback()>------------
}

 

 
Mobile
»
Asp.Net Core: Eigenen Email Provider einbinden
»
Chrome: wie kann man die Browser Informationen in Asp.Net Core 2 MVC ermitteln und anzeigen.
»
Client Auswertung mit Wangkanai Detection
»
Browser in Asp.Net Core 2 mit Wangkanai
»
Asp.Net Core 2 MVC: Email Sender Client schreiben.
»
Asp core: Cookie lesen und schreiben
»
Asp: Bild aktualisiert anzeigen trotz Browser Cache
»
Asp MVC: Formatiere Datum als Kurzes Datum
»
Asp MVC Core: HTML Text als HTML Elemente anzeigen
»
Asp: HTML in Text umwandeln

.

Jobs, Projekte, Angebote für Freiberufler, Selbstständig an Info@CodeDocu.de