public EmailService() { _templates = new EmailTemplates(); _mailMessage = new MailMessage(); _smtpClient = new SmtpClient(); _mjrMailAddress = new MailAddress("*****@*****.**", "No-Reply Mjr"); InitializeFields(); }
private List<Email> GetFromTemplates(EmailTemplates templates) { var emails = new List<Email>(); foreach (EmailTemplate t in templates) { emails.Add(new Email { EmailLabel = t.EmailLabel, FromAddress = t.FromAddress, DateUpdated = t.DateUpdated }); } return emails; }
public async Task <string> Email() { string recepientName = "ASCA Tester"; // <===== Put the recepient's name here string recepientEmail = "*****@*****.**"; // <===== Put the recepient's email here string message = EmailTemplates.GetTestEmail(recepientName, DateTime.UtcNow); (bool success, string errorMsg)response = await _emailer.SendEmailAsync(recepientName, recepientEmail, "Test Email from Transmaquila", message); if (response.success) { return("Success"); } return("Error: " + response.errorMsg); }
public async Task <string> Email() { string recepientName = "Wasa Community Tester"; // <===== Put the recepient's name here string recepientEmail = "*****@*****.**"; // <===== Put the recepient's email here string message = EmailTemplates.GetTestEmail(recepientName, DateTime.UtcNow); (bool success, string errorMsg)response = await _emailer.SendEmailAsync(recepientName, recepientEmail, "Test Email from Wasa Community", message); if (response.success) { return("Success"); } return("Error: " + response.errorMsg); }
public async Task <string> Email() { string recepientName = "Kiril Zafirov"; // <===== Put the recepient's name here string recepientEmail = "*****@*****.**"; // <===== Put the recepient's email here string message = EmailTemplates.GetTestEmail(recepientName, DateTime.UtcNow); (bool success, string errorMsg) = await _emailer.SendEmailAsync(recepientName, recepientEmail, "Test Email from Ruen", message); if (success) { return("Success"); } return("Error: " + errorMsg); }
public async Task <string> Email() { string recepientName = "QickApp Tester"; // <===== Put the recepient's name here string recepientEmail = "*****@*****.**"; // <===== Put the recepient's email here string message = EmailTemplates.GetTestEmail(recepientName, DateTime.UtcNow); (bool success, string errorMsg) = await _emailSender.SendEmailAsync(recepientName, recepientEmail, "Test Email from QuickApp", message); if (success) { return("Success"); } return("Error: " + errorMsg); }
public async Task <string> Email() { string recepientName = "QickApp Tester"; // <===== Put the recepient's name here string recepientEmail = "*****@*****.**"; // <===== Put the recepient's email here string message = EmailTemplates.GetTestEmail(recepientName, DateTime.UtcNow); (bool success, string errorMsg)response = await _emailer.SendEmailAsync(recepientName, recepientEmail, "Test Email from Quick_Application2", message); if (response.success) { return("Success"); } return("Error: " + response.errorMsg); }
public async Task <string> Email() { string recepientName = "QickApp Tester"; string recepientEmail = "*****@*****.**"; string message = EmailTemplates.GetTestEmail(recepientName, DateTime.UtcNow); (bool success, string errorMsg) = await _emailer.SendEmailAsync(recepientName, recepientEmail, "Test Email from QuickApp", message); if (success) { return("Success"); } return("Error: " + errorMsg); }
public async Task <string> Email() { string recepientName = "QickApp Tester"; // <===== Put the recepient's name here string recepientEmail = "*****@*****.**"; // <===== Put the recepient's email here string message = EmailTemplates.GetTestEmail(recepientName, DateTime.UtcNow); (bool success, string errorMsg) = await _emailSender.SendEmailAsync(recepientName, recepientEmail, "Test Email from AspnetCoreAngularVanila", message); if (success) { return("Success"); } return("Error: " + errorMsg); }
public static void SaveEmailTemplate(int emailTemplateID, string subject, string header, string footer, string body, bool isHtml, bool useTemplate, int productFamilyID) { if (!UserSession.CurrentUser.IsSystemAdmin) { return; } EmailTemplate template = EmailTemplates.GetEmailTemplate(UserSession.LoginUser, emailTemplateID); subject = template.IsEmail ? subject : ""; if (UserSession.LoginUser.UserID == -34) { template.Body = body; template.EmailTemplateID = emailTemplateID; template.IsHtml = isHtml; template.Subject = subject; template.Header = header; template.Footer = footer; template.UseGlobalTemplate = useTemplate && template.IsEmail; template.Collection.Save(); } else { OrganizationEmails emails = new OrganizationEmails(UserSession.LoginUser); emails.LoadByTemplateAndProductFamily(UserSession.LoginUser.OrganizationID, emailTemplateID, productFamilyID); OrganizationEmail email = emails.IsEmpty || (emails[0].ProductFamilyID == null && productFamilyID != -1) ? (new OrganizationEmails(UserSession.LoginUser)).AddNewOrganizationEmail() : emails[0]; email.Body = body; email.EmailTemplateID = emailTemplateID; email.IsHtml = isHtml; email.OrganizationID = UserSession.LoginUser.OrganizationID; email.Subject = subject; email.Header = header; email.Footer = footer; email.UseGlobalTemplate = useTemplate && template.IsEmail; if (productFamilyID == -1) { email.ProductFamilyID = null; } else { email.ProductFamilyID = productFamilyID; } email.Collection.Save(); } }
public async Task <ActionResult> RecoverAsync(RecoverViewModel model) { var requester = UserIdentity.GetRequester(this); var userName = model.UserName; AppSensor.ValidateFormData(this, new List <string> { "UserName" }); if (ModelState.IsValid) { var user = _context.User.SingleOrDefault(u => u.UserName == model.UserName && u.Enabled && u.EmailVerified && u.Approved); if (_configuration.HasRecaptcha) { if (!_recaptcha.ValidateRecaptcha(this)) { Logger.Information("Failed Account Recover Post Recaptcha failed by requester {@requester}", requester); return(View("Recover", model)); } } if (user != null) { user.PasswordResetToken = Guid.NewGuid().ToString().Replace("-", ""); user.PasswordResetExpiryDateUtc = DateTime.UtcNow.AddMinutes(15); // Send recovery email with link to recover password form string emailBody = EmailTemplates.ChangePasswordPendingBodyText(user.FirstName, user.LastName, _configuration.ApplicationName, _configuration.WebsiteBaseUrl, user.PasswordResetToken); string emailSubject = $"{_configuration.ApplicationName} - Complete the password recovery process"; _services.SendEmail(_configuration.DefaultFromEmailAddress, new List <string>() { user.UserName }, null, null, emailSubject, emailBody, true); user.UserLogs.Add(new UserLog { Description = "Password reset link generated and sent" }); await _context.SaveChangesAsync(); } else { Logger.Information("Failed Account Recover Post UserName {userName} by requester {@requester}", userName, requester); return(View("RecoverSuccess")); } } else { AppSensor.InspectModelStateErrors(this); } return(View("RecoverSuccess")); }
public async Task <ApiResponse> ResetPassword(ResetPasswordDto parameters) { if (!ModelState.IsValid) { return(new ApiResponse(400, "User Model is Invalid")); } var user = await _userManager.FindByIdAsync(parameters.UserId); if (user == null) { _logger.LogInformation("User does not exist: {0}", parameters.UserId); return(new ApiResponse(404, "User does not exist")); } #region Reset Password Successful Email try { IdentityResult result = await _userManager.ResetPasswordAsync(user, parameters.Token, parameters.Password); if (result.Succeeded) { #region Email Successful Password change var email = new EmailMessageDto(); email.ToAddresses.Add(new EmailAddressDto(user.Email, user.Email)); email = EmailTemplates.BuildPasswordResetEmail(email, user.UserName); //Replace First UserName with Name if you want to add name to Registration Form _logger.LogInformation("Reset Password Successful Email Sent: {0}", user.Email); await _emailService.SendEmailAsync(email); #endregion return(new ApiResponse(200, String.Format("Reset Password Successful Email Sent: {0}", user.Email))); } else { _logger.LogInformation("Error while resetting the password!: {0}", user.UserName); return(new ApiResponse(400, string.Format("Error while resetting the password!: {0}", user.UserName))); } } catch (Exception ex) { _logger.LogInformation("Reset Password failed: {0}", ex.Message); return(new ApiResponse(400, string.Format("Error while resetting the password!: {0}", ex.Message))); } #endregion }
public async Task <ActionResult> ChangeEmailAddress(ChangeEmailAddressViewModel model) { var userId = _userIdentity.GetUserId(this); var user = _context.User.Where(u => u.Id == userId && u.Enabled && u.EmailVerified && u.Approved).FirstOrDefault(); _appSensor.ValidateFormData(this, new List <string>() { "NewEmailAddress", "Password" }); if (ModelState.IsValid) { var logonResult = await _userManager.TryLogOnAsync(_userIdentity.GetUserName(this), model.Password); if (logonResult.Success) { if (user != null) { user.NewEmailAddressToken = Guid.NewGuid().ToString().Replace("-", ""); user.NewEmailAddressRequestExpiryDate = DateTime.UtcNow.AddMinutes(15); user.NewEmailAddress = model.NewEmailAddress; // Send change username with link to recover password form string emailBody = EmailTemplates.ChangeEmailAddressPendingBodyText(user.FirstName, user.LastName, _configuration.ApplicationName, _configuration.WebsiteBaseUrl, user.NewEmailAddressToken); string emailSubject = string.Format("{0} - Complete the change email address process", _configuration.ApplicationName); _services.SendEmail(_configuration.DefaultFromEmailAddress, new List <string>() { user.UserName }, null, null, emailSubject, emailBody, true); user.UserLogs.Add(new UserLog() { Description = string.Format("Change email address request started to change from {0} to {1}", user.UserName, user.NewEmailAddress) }); _context.SaveChanges(); return(View("ChangeEmailAddressPending")); } } else { Logger.Information("Failed Account ChangeEmailAddress Post, Password incorrect by requester {@requester}", _userIdentity.GetRequester(this, Core.Constants.AppSensorDetectionPointKind.AE1)); ModelState.AddModelError("Password", "The password is not correct"); } } else { _appSensor.InspectModelStateErrors(this); } return(View(new ChangeEmailAddressViewModel(user.UserName, user.NewEmailAddress, user.NewEmailAddressRequestExpiryDate))); }
public async Task <ApiResponse> Send(EmailDto parameters) { if (!ModelState.IsValid) { return(new ApiResponse(400, "User Model is Invalid")); } var email = new EmailMessageDto(); email.ToAddresses.Add(new EmailAddressDto(parameters.ToName, parameters.ToAddress)); //This forces all emails from the API to use the Test template to prevent spam parameters.TemplateName = "Test"; //Send a Template email or a custom one since it is hardcoded to Test template it will not do a custom email. if (!string.IsNullOrEmpty(parameters.TemplateName)) { switch (parameters.TemplateName) { case "Test": email = EmailTemplates.BuildTestEmail(email); //example of email Template usage break; default: break; } } else { email.Subject = parameters.Subject; email.Body = parameters.Body; } //Add a new From Address if you so choose, default is set in appsettings.json //email.FromAddresses.Add(new EmailAddress("New From Name", "*****@*****.**")); _logger.LogInformation("Test Email: {0}", email.Subject); try { await _emailService.SendEmailAsync(email); return(new ApiResponse(200, "Email Successfuly Sent")); } catch (Exception ex) { return(new ApiResponse(500, ex.Message)); } }
private string ProcessMessage(EmailTemplates template, string message, string subject) { string output = LoadTemplate(template); output = output.Replace("{footer}", string.Format("For more information please visit <a href=\"{0}\">{1}</a>", LibLogic.Helpers.SiteInfo.SiteUrl, LibLogic.Helpers.SiteInfo.SiteName)); if (template == EmailTemplates.BetaKey || template == EmailTemplates.Generic) { output = output.Replace("{subject}", subject); output = output.Replace("{message}", message); return(output); } return(message); }
public ApiControllerRegistrationBase( string resource, RoleManager <IdentityRole> roleManager, UserManager <TUser> userManager, SignInManager <TUser> signInManager, TokenSettings tokenSettings, IUrlHelper urlHelper, IEmailService emailSender, IMapper mapper, PasswordSettings passwordSettings, EmailTemplates emailTemplates, AppSettings appSettings, IAuthorizationService authorizationService) : base(resource, roleManager, userManager, signInManager, tokenSettings, urlHelper, emailSender, mapper, passwordSettings, emailTemplates, appSettings, authorizationService) { _welcomeEmailTemplate = emailTemplates.Welcome; }
public JsonResult Add(EmailTemplateVModel model) { var result = new JsonResultModel(); if (ModelState.IsValid) { //add result.ResultState = EmailTemplates.AddEmailTemplate(EmailTemplates.EmailTemplateVModelToInfo(model)) > 0; } else { result.ResultState = false; result.Message = ModelStateHelper.GetAllErrorMessage(ModelState); } return(Json(result)); }
public void GetPlainTextTestEmail_WhenInvoke_ShouldReturnNotNullEmailMessage() { _webHostEnvMock.DefaultValue = DefaultValue.Mock; var provider = _webHostEnvMock.Object.ContentRootFileProvider; var providerMock = Mock.Get(provider); var fileMock = new PhysicalFileInfo (new FileInfo(_fileInfoPath)); providerMock.Setup(x => x.GetFileInfo(It.IsAny <string>())) .Returns(fileMock); EmailTemplates.Initialize(_webHostEnvMock.Object); DateTime testDate = new DateTime(2020, 1, 1); string emailMessage = EmailTemplates.GetPlainTextTestEmail(testDate); Assert.IsNotNull(emailMessage); }
/// <summary> /// Get email templates based on request parameters /// </summary> /// <param name="request">Request parameters</param> /// <returns>EmailTemplatesResponse</returns> public object Get(GetEmailTemplates request) { EmailTemplatePageCriteria pageCriteria = new EmailTemplatePageCriteria(); pageCriteria.PageSize = request.PageSize == 0 ? 10 : request.PageSize; pageCriteria.SortBy = request.SortBy; pageCriteria.Page = request.Page == 0 ? 1 : request.Page; EmailTemplates templates = new EmailTemplates(); templates.LoadCriteria(pageCriteria); templates.Load(); return(new EmailTemplatesResponse { templates = templates, total = templates.TotalCount }); }
public void NewPostEmail(IEnumerable <Subscription> Subs, Post ThePost, Thread thread, string PostURL) { ListDictionary replacements = new ListDictionary(); string AutoFromEmail = SiteConfig.AutomatedFromEmail.Value; MailDefinition md = new MailDefinition(); md.BodyFileName = EmailTemplates.GenerateEmailPath(EmailTemplates.NewThreadReply); md.IsBodyHtml = true; md.From = AutoFromEmail; md.Subject = "Reply to Thread '" + thread.Title + "' - " + SiteConfig.BoardName.Value; replacements.Add("{REPLY_USERNAME}", ThePost.User.Username); replacements.Add("{REPLY_TEXT}", ThePost.Text); replacements.Add("{THREAD_TITLE}", thread.Title); replacements.Add("{POST_URL}", PostURL); replacements.Add("{BOARD_URL}", SiteConfig.BoardURL.Value); replacements.Add("{BOARD_NAME}", SiteConfig.BoardName.Value); System.Web.UI.Control ctrl = new System.Web.UI.Control { ID = "Something" }; MailMessage message = md.CreateMailMessage("*****@*****.**", replacements, ctrl); //Send the message SmtpClient client = Settings.GetSmtpClient(); foreach (Subscription s in Subs) { if (s.UserID == ThePost.UserID) { continue; } User u = s.User; message.To.Clear(); message.To.Add(u.Email); try { System.Threading.ThreadPool.QueueUserWorkItem(state => client.Send(message)); } catch { } } }
public async Task <JsonResult> GetScheduleStudent(Guid?classId, Guid?studentId, int page, int size) { var list = this._unitOfWork.Classes.GetScheduleStudent( classId, studentId, page, size); var results = new List <ClassList>(); var html = string.Empty; if (list != null && list.Count > 0) { results = list.Select(p => new ClassList { ClassId = p.ClassId, ClassName = p.ClassName, LearnDate = p.LearnDate, NoteClass = p.NoteClass, TodayName = p.TodayName, StudentId = p.StudentId, MaterialId = p.StudentId, MaterialCode = p.MaterialCode, MaterialName = p.MaterialName, IsLearnMain = p.IsLearnMain, Absent = p.IsPause == true ? 4 : (p.LearnAbsent == true ? 2 : p.LearnAbsent == false ? 1 : 0), StartTime = p.StartTime, EndTime = p.EndTime }).ToList(); // get html var branch = await GetBranch(); var student = await this._unitOfWork.Students.Get(studentId); var cl = await this._unitOfWork.Classes.Get(classId); var sup = await this._unitOfWork.Suppliers.Get(cl.SupplierId); html = EmailTemplates.GetTemplate_Schedules(_serviceSmtpConfig, results.ToArray(), branch, student, cl, sup); } return(Json(new { Total = this._unitOfWork.Classes.Total, List = results, Html = html })); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IApplicationDbContextSeed applicationDbContextSeed) { EmailTemplates.Initialize(env); using (var serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope()) { serviceScope.ServiceProvider.GetService <ApplicationDbContext>().Database.Migrate(); } app.UseResponseCompression(); // This must be before the other Middleware if that manipulates Response app.UseMiddleware <UserSessionMiddleware>(); // A REST API global exception handler and response wrapper for a consistent API // Configure API Loggin in appsettings.json - Logs most API calls. Great for debugging and user activity audits app.UseMiddleware <APIResponseRequestLogginMiddleware>(Convert.ToBoolean(Configuration["BlazorBoilerplate:EnableAPILogging"] ?? "true")); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBlazorDebugging(); } //else //{ // // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. // app.UseHsts(); //HSTS Middleware (UseHsts) to send HTTP Strict Transport Security Protocol (HSTS) headers to clients. //} app.UseClientSideBlazorFiles <Client.Startup>(); //app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); // NSwag app.UseOpenApi(); app.UseSwaggerUi3(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); endpoints.MapFallbackToClientSideBlazor <Client.Startup>("index.html"); }); applicationDbContextSeed.SeedDb(); }
public async Task <IActionResult> ActivateUser(string id) { ApplicationUser appUser = await this._accountManager.GetUserByIdAsync(id); if (appUser == null) { return(NotFound(id)); } appUser.IsEnabled = true; var result = await _accountManager.UpdateUserAsync(appUser); if (result.Item1) { var recipients = new EmailAddress[] { new EmailAddress { Name = appUser.FirstName + " " + appUser.LastName, Email = appUser.Email } }; var requestParam = new Dictionary <string, string> { { "{fullName}", appUser.FirstName + " " + appUser.LastName } }; var response = await EmailSender.SendEmailAsync( recipients, subject : "Adam.info Account Information", content : EmailTemplates.GetAccountActivatedEmail(requestParam, "en"), isHtml : true, addBccs : true); if (!response.Item1) { this.logger.LogWarning(new EventId(1, "Email Error"), null, $"Failed to send Email Error: {response.Item2}"); } } else { throw new Exception("The following errors occurred whilst activating user: "******", ", result.Item2)); } return(NoContent()); }
public async Task <ActionResult> ChangeEmailAddressConfirm() { var newEmaiLAddressToken = Request.QueryString["NewEmailAddressToken"] ?? ""; var user = _context.User.Where(u => u.NewEmailAddressToken == newEmaiLAddressToken && u.NewEmailAddressRequestExpiryDate > DateTime.UtcNow).FirstOrDefault(); var requester = _userIdentity.GetRequester(this); if (user == null) { HandleErrorInfo error = new HandleErrorInfo(new ArgumentException("INFO: The new user name token is not valid or has expired"), "Account", "ChangeEmailAddressConfirm"); Logger.Information("Failed Account ChangeEmailAddressConfirm Get, The new user name token is not valid or has expired by requester {@requester}", requester); return(View("Error", error)); } if (user.Enabled == false) { HandleErrorInfo error = new HandleErrorInfo(new InvalidOperationException("INFO: Your account is not currently approved or active"), "Account", "ChangeEmailAddressConfirm"); Logger.Information("Failed Account ChangeEmailAddressConfirm Get, Account is not currently approved or active by requester {@requester}", requester); return(View("Error", error)); } user.UserLogs.Add(new UserLog() { Description = string.Format("Change email address request confirmed to change from {0} to {1}", user.UserName, user.NewEmailAddress) }); string emailSubject = string.Format("{0} - Change email address process completed", _configuration.ApplicationName); string emailBody = EmailTemplates.ChangeEmailAddressCompletedBodyText(user.FirstName, user.LastName, _configuration.ApplicationName, user.UserName, user.NewEmailAddressToken); _services.SendEmail(_configuration.DefaultFromEmailAddress, new List <string>() { user.UserName }, null, null, emailSubject, emailBody, true); user.UserName = user.NewEmailAddress; user.NewEmailAddress = null; user.NewEmailAddressRequestExpiryDate = null; user.NewEmailAddressToken = null; emailBody = string.Format("A request has been completed to change your {0} username/email address to {1}. This email address can now be used to log into the application.", _configuration.ApplicationName, user.UserName); _services.SendEmail(_configuration.DefaultFromEmailAddress, new List <string>() { user.UserName }, null, null, emailSubject, emailBody, true); await _context.SaveChangesAsync(); _userManager.SignOut(); return(View("ChangeEmailAddressSuccess")); }
public void SendMail(string message, string subject, string to, bool isHtml, byte[] attachment = null, EmailTemplates template = EmailTemplates.None) { var mm = new MailMessage(); var smcl = new SmtpClient(); mm.To.Add(to); string sendMessage = message; if (template != EmailTemplates.None) { sendMessage = ProcessMessage(template, message, subject); } mm.From = new MailAddress("*****@*****.**"); mm.IsBodyHtml = isHtml; mm.Body = sendMessage; mm.Subject = subject; if (attachment != null) { var attachData = new System.Net.Mail.Attachment(new MemoryStream(attachment), ""); mm.Attachments.Add(attachData); } smcl.Host = "smtp.gmail.com"; smcl.Port = 587; smcl.Credentials = new NetworkCredential("*****@*****.**", "AG687@5345@#4aegsdfghgdgASD346y6789$%T@adfaDSF"); smcl.EnableSsl = true; // This line is very bad. It will always say the smtp server ssl is valid even if it is not. // This is required because mono on linux does not have gmail ssl certs and there is no way to auto import // them using vagrant. See bootstrap file "bootstrap-website.sh" function "configure_gmail_ssl_certs_for_mono" // or // mozroots --import --ask-remove --machine // certmgr -ssl smtps://smtp.gmail.com:465 // certmgr -ssl smtps://smtp.gmail.com:587 ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); }; smcl.Send(mm); }
public async Task <IActionResult> Send(EmailParameters parameters) { if (!ModelState.IsValid) { return(BadRequest(ModelState.Values.SelectMany(state => state.Errors) .Select(error => error.ErrorMessage) .FirstOrDefault())); } var email = new EmailMessage(); email.ToAddresses.Add(new EmailAddress(parameters.ToName, parameters.ToAddress)); //This forces all emails from the API to use the Test template to prevent spam parameters.TemplateName = "Test"; //Send a Template email or a custom one since it is hardcoded to Test template it will not do a custom email. if (!string.IsNullOrEmpty(parameters.TemplateName)) { switch (parameters.TemplateName) { case "Test": email = EmailTemplates.BuildTestEmail(email); //example of email Template usage break; default: break; } } else { email.Subject = parameters.Subject; email.Body = parameters.Body; } //Add a new From Address if you so choose, default is set in appsettings.json //email.FromAddresses.Add(new EmailAddress("New From Name", "*****@*****.**")); _logger.LogInformation("Test Email: {0}", email.Subject); await _emailService.SendEmailAsync(email); return(Ok(new { success = "true" })); }
public bool GetTemplateFileContents(EmailTemplates enmEmailTemplate, out string strTemplateContents) { strTemplateContents = string.Empty; try { // Calculate the template names using the enum type name string strEmailTemplateDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).Replace("file:\\", ""); // //Directory.GetCurrentDirectory() string strTemplateFilePath = System.IO.Path.Combine(strEmailTemplateDirectory, "Content", String.Concat(enmEmailTemplate.ToString(), ".html")); strTemplateContents = System.IO.File.ReadAllText(strTemplateFilePath); } catch (Exception ex) { _lstErrorMessages.Add(String.Concat("There was an exception while trying to retrieve the contents of the Email Template file from disk. Error Message = [", ex.Message, "]")); } return(_lstErrorMessages.Count == 0); }
public async Task <IActionResult> RecoverPassword([FromBody] UserPasswordRecovery recoveryInfo) { if (ModelState.IsValid) { ApplicationUser appUser = null; if (recoveryInfo.UsernameOrEmail.Contains("@")) { appUser = await _accountManager.GetUserByEmailAsync(recoveryInfo.UsernameOrEmail); } if (appUser == null) { appUser = await _accountManager.GetUserByUserNameAsync(recoveryInfo.UsernameOrEmail); } //if (appUser == null || !(await _accountManager.IsEmailConfirmedAsync(appUser))) //{ // // Don't reveal that the user does not exist or is not confirmed // return Accepted(); //} if (appUser == null) { // Don't reveal that the user does not exist or is not confirmed return(Accepted()); } string code = await _accountManager.GeneratePasswordResetTokenAsync(appUser); string callbackUrl = $"{_config.Value.EmailEndUrl}/ResetPassword?code={code}"; string message = EmailTemplates.GetResetPasswordEmail(appUser.UserName, appUser.Email, HtmlEncoder.Default.Encode(callbackUrl)); //string code = await _accountManager.GeneratePasswordResetTokenAsync(appUser); //string callbackUrl = $"{Request.Scheme}://{Request.Host}/ResetPassword?code={code}"; //string message = EmailTemplates.GetResetPasswordEmail(appUser.UserName, appUser.Email, HtmlEncoder.Default.Encode(callbackUrl)); await _emailSender.SendEmailAsync(appUser.UserName, appUser.Email, "Reset Password", message); return(Accepted()); } return(BadRequest(ModelState)); }
public async Task <IActionResult> ArchiveUser(string id) { var callerId = GetIdFromClaims(); if (callerId != id) { return(BadRequest("You can only archive your own account.")); } await _userService.Archive(id); var user = await _userService.GetUser(id); var email = EmailTemplates.GetArchivedAccountEmail(); await _emailService.SendAsync(user.Email, "Archived Account", email); _logger.LogInformation("Forgot password email sent successfully."); return(Ok()); }
private async Task SendConfirmationEmail(Opportunity opportunity) { //add the necessary parameters for opportunity management var parameterDictionary = new Dictionary <string, string>(); parameterDictionary.Add("EditId", opportunity.EditId); parameterDictionary.Add("ActivationId", opportunity.ActivationId); parameterDictionary.Add("DeleteId", opportunity.DeleteId); var emailBody = EmailTemplates.GetTemplate("OpportunityAdminEmail.html", parameterDictionary); var opportunityAdminEmail = new EmailMessage { Subject = $"ACTION REQUIRED: Your ImmuneAndReadyToHelp.com Opportunity ({opportunity.Title}) Is Almost Live!", Body = emailBody, To = EmailOfOpportunityContact }; await EmailService.Send(opportunityAdminEmail); }
public async Task <IActionResult> ForgotPassword(ForgotPasswordParameters parameters) { if (!ModelState.IsValid) { return(BadRequest(ModelState.Values.SelectMany(state => state.Errors) .Select(error => error.ErrorMessage) .FirstOrDefault())); } var user = await _userManager.FindByEmailAsync(parameters.Email); if (user == null || !(await _userManager.IsEmailConfirmedAsync(user))) { _logger.LogInformation("Forgot Password with non-existent email / user: {0}", parameters.Email); // Don't reveal that the user does not exist or is not confirmed return(Ok(new { success = "true" })); } #region Forgot Password Email try { // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713 var token = await _userManager.GeneratePasswordResetTokenAsync(user); string callbackUrl = string.Format("{0}/Account/ResetPassword/{1}?token={2}", _configuration["ApplicationUrl"], user.Id, token); //token must be a query string parameter as it is very long var email = new EmailMessage(); email.ToAddresses.Add(new EmailAddress(user.Email, user.Email)); email.FromAddresses.Add(new EmailAddress("*****@*****.**", "*****@*****.**")); email = EmailTemplates.BuildForgotPasswordEmail(email, user.UserName, callbackUrl, token); //Replace First UserName with Name if you want to add name to Registration Form _logger.LogInformation("Forgot Password Email Sent: {0}", user.Email); await _emailService.SendEmailAsync(email); } catch (Exception ex) { _logger.LogInformation("Forgot Password email failed: {0}", ex.Message); } #endregion return(Ok(new { success = "true" })); }
public async Task <IActionResult> ForgotPassword([FromBody] ForgotPasswordBindingModel bm) { if (bm == null) { return(BadRequest("The payload must not be null.")); } if (string.IsNullOrWhiteSpace(bm.Email)) { return(BadRequest("An email address is required.")); } var user = await _userService.GetUserByEmail(bm.Email); if (user == null) { return(NotFound("A user with that email address doesn't exist.")); } var token = Helpers.GetToken(user, 12, TokenType.Reset); var email = EmailTemplates.GetForgotPasswordEmail( $"{Config.FrontEndUrl}/auth/reset-password?token={token}"); var response = await _emailService.SendAsync(bm.Email, "Forgot Password", email); if (response.IsSuccessful) { _logger.LogInformation("Forgot password email sent successfully."); return(Ok(new GenericViewModel { Message = "Your password reset email has been sent." })); } _logger.LogError("The email was not sent successfully."); _logger.LogError(response.ErrorException, response.ErrorMessage); return(StatusCode((int)HttpStatusCode.InternalServerError, new GenericViewModel { Message = "An error occurred when sending the recovery email." })); }