public async Task SendConfirmationEmail(ConfirmationEmail request, string link) { //string filePath = Directory.GetCurrentDirectory() + "\\Templates\\ConfirmationEmailTemplate.html"; string wwwRootPath = _hostEnvironment.WebRootPath; string path = wwwRootPath + "/templates/ConfirmationEmailTemplate.html"; StreamReader reader = new StreamReader(path); string mailText = reader.ReadToEnd(); reader.Close(); mailText = mailText .Replace("[username]", request.UserName) .Replace("[email]", request.ToEmail) .Replace("[link]", link); // check html var email = new MimeMessage(); email.Sender = MailboxAddress.Parse(_mailSettings.Mail); email.To.Add(MailboxAddress.Parse(request.ToEmail)); email.Subject = $"Email verification for {request.ToEmail}"; var builder = new BodyBuilder(); builder.HtmlBody = mailText; email.Body = builder.ToMessageBody(); using var smtp = new SmtpClient(); smtp.Connect(_mailSettings.Host, _mailSettings.Port, SecureSocketOptions.StartTls); smtp.Authenticate(_mailSettings.Mail, _mailSettings.Password); await smtp.SendAsync(email); smtp.Disconnect(true); }
public RewriterService(ConfirmationEmail confirmationEmail) { AssertNotNull(confirmationEmail); this.confirmationEmail = confirmationEmail; this.logger = LogManager.GetCurrentClassLogger(); }
public async Task <IActionResult> RegisterAsync([FromBody] RegisterUser registerUser, string confirmationRedirectUrl = null) { if (!ModelState.IsValid) { return(new BadRequestObjectResult(ModelState)); } var accountEntity = registerUser.ToAccountEntity(); var result = await this.userManager.CreateAsync(accountEntity, registerUser.Password); if (result.Succeeded) { // Send out confirmation email try { var emailConfirmationToken = await this.userManager.GenerateEmailConfirmationTokenAsync(accountEntity); var confirmationUrl = string.Empty; if (string.IsNullOrWhiteSpace(confirmationRedirectUrl)) { confirmationUrl = this.Url.RouteUrl("ConfirmEmail", new { userId = accountEntity.Id, token = emailConfirmationToken }, "http", this.Request.Host.Value); } else { try { var uriBuilder = new UriBuilder(confirmationRedirectUrl); var query = HttpUtility.ParseQueryString(uriBuilder.Query); query["userId"] = HttpUtility.UrlEncode(accountEntity.Id); query["token"] = HttpUtility.UrlEncode(emailConfirmationToken); uriBuilder.Query = query.ToString(); confirmationUrl = uriBuilder.ToString(); } catch (UriFormatException ex) { // TODO Logging return(new BadRequestObjectResult("Invalid RedirectUrl: Has to be an absolute path to the confirmation view.")); } } await this.emailService.SendEmailAsync(ConfirmationEmail.Create(accountEntity.Email, confirmationUrl, accountEntity.FirstName)); return(new OkObjectResult(new RegisterResult { Success = true })); } catch (Exception ex) { // TODO Logging return(new StatusCodeResult(500)); } } // TODO send errors return(new OkObjectResult(new RegisterResult { Success = false })); }
private void SendEmails(IEnumerable <Confirmation> confirmations) { foreach (var confirmation in confirmations) { var email = new ConfirmationEmail("Confirmation", confirmation); email.SendAsync(); } }
public async Task <IActionResult> Register(string username, string email, string firstName, string lastName, string password) { var user = new User { UserName = username, Email = email, FirstName = firstName, LastName = lastName }; ValidationResult validationResult = _userValidator.Validate(user); List <string> errors = new List <string>(); if (!validationResult.IsValid) { foreach (var error in validationResult.Errors) { errors.Add(error.ErrorMessage); } return(BadRequest(errors)); } var result = await _userManager.CreateAsync(user, password); if (result.Succeeded) { // generate email token var token = await _userManager.GenerateEmailConfirmationTokenAsync(user); //token = HttpUtility.UrlEncode(token); var link = Url.Action(nameof(VerifyEmail), "Account", new { userId = user.Id, token }, Request.Scheme, Request.Host.ToString()); var newLink = @"https://*****:*****@"http://chatdemo.local/Account/VerifyEmail?userId=" + user.Id + "&token=" + HttpUtility.UrlEncode(token); ConfirmationEmail request = new ConfirmationEmail { ToEmail = user.Email, UserName = user.UserName }; await _mailService.SendConfirmationEmail(request, link); return(Ok()); } foreach (var error in result.Errors) { errors.Add(error.Description); } return(BadRequest(errors)); }
public Boolean SendEmailRecoverPassword(ConfirmationEmail confirmation) { string emailBody = "<p>Respetado<p>" + "<p>Usuario</p>"; emailBody = emailBody + "<br><p>Para recuperar su contraseña en el Sistema de IAS haga click <a href=" + confirmation.CallBack + ">aquí</a></p><br>"; emailBody += "<p>Cordialmente,</p><br>"; emailBody += "</p>IAS</p>"; emailBody += "</p>IAS</p>"; return(SendEmail(confirmation.Email, AFFAIR, emailBody)); }
public async Task <HttpStatusCode> SendCofirmationEmail(string username, string emailAddress, Guid emailToken) { var url = BananaHttpContext.AppBaseUrl + "/api/v1/users/registration-complete/" + emailToken; var objectData = new ConfirmationEmail() { Username = username, Url = url }; var result = await Send("Bulee Services", username, emailAddress, "*****@*****.**", templateId, objectData); return(result); }
public async Task <IActionResult> ForgotPassword(ForgotPasswordVM model) { var user = await userManager.FindByEmailAsync(model.Email); if (user != null) { List <string> roles = await userManager.GetRolesAsync(user) as List <string>; var rol = roleManager.Roles.FirstOrDefault(x => x.Name == roles[0]); if (rol.IsExternal) { string resetToken = await userManager.GeneratePasswordResetTokenAsync(user); string tokenEncode = System.Web.HttpUtility.UrlEncode(resetToken); ConfirmationEmail confirmEmail = new ConfirmationEmail { Email = user.Email }; confirmEmail.CallBack = Url.Action("RecoverPassword", "Account", new { area = "Identity", token = tokenEncode, // reset token u = user.Id // user token, use GUID user id or Usuario.PublicToken }, protocol: Request.Scheme); Boolean emailSent = EmailComm.SendEmailRecoverPassword(confirmEmail); if (emailSent) { CreateModal("exito", "Terminado", "Se ha enviado correo electrónico para completar el proceso.", "Continuar", null, "Redirect('/')", null); return(View(model)); } else { CreateModal("error", "Error", "No se ha podido enviar el email, intente de nuevo mas tarde.", "Continuar", null, "Redirect('/')", null); return(View(model)); } } else { CreateModal("error", "Error", "No es posible realizar la operación.", "Continuar", null, "Redirect('/')", null); return(View(model)); } } else { CreateModal("error", "Error", "No se encontró usuario asociado al email", "Continuar", null, "Redirect('/')", null); return(View(model)); } }
public IHttpActionResult Create([FromBody] RegistrationViewModel data) { try { var eventItem = _eventRepository.GetById(data.EventId); var visitor = _visitorRepository.GetByEmail(data.Email); if (visitor == null) { visitor = Visitor.Create(data.Name, data.City, data.Email, data.Postcode); _visitorRepository.Insert(visitor); } var numberOfVisitors = Convert.ToInt32(data.NumberOfVisitors); var registration = Registration.Create(visitor, eventItem, numberOfVisitors, false); registration.Confirmed = true; registration.ConfirmationDate = DateTime.Now; _registrationRepository.Insert(registration); var logoUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority) + "/img"; var barcodeUrl = @"https://chart.googleapis.com/chart?chl=" + Uri.EscapeUriString(registration.Id.ToString()) + @"&chs=200x200&cht=qr&chld=H%7C0"; var settings = _settingRepository.GetById(1); ConfirmationEmail email = new ConfirmationEmail() { To = visitor.Email, Name = visitor.Name, Date = eventItem.TimeRange.Start.ToString("dd-MM-yyyy"), TimeFrom = eventItem.TimeRange.Start.ToShortTimeString(), TimeTill = eventItem.TimeRange.End.ToShortTimeString(), NumberOfVisitors = registration.NumberOfVisitors, LogoUrl = logoUrl, BarcodeUrl = barcodeUrl, RegistrationId = registration.Id.ToString(), Disclaimer = settings.EmailDisclaimer, }; email.Send(); return(Ok(new { message = "Registratie is verzonden en bevestigd" })); } catch (Exception e) { return(BadRequest(e.Message)); } }
public static void SendConfirmationEmail(Guid id) { var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails")); var engines = new ViewEngineCollection(); engines.Add(new FileSystemRazorViewEngine(viewsPath)); var emailService = new EmailService(engines); using (var db = new MailerDbContext()) { var m = db.ConfirmationEmails.Find(id); ConfirmationEmail em = new ConfirmationEmail(); em.Name = m.Name; em.Surname = m.Surname; em.To = m.Email; em.Attachments.Add(new System.Net.Mail.Attachment(m.QRCodePath)); emailService.Send(em); } }
//Waiting on Template public async Task Register(ConfirmationEmail model) { Register register = new Register(); var msg = new SendGridMessage() { From = new EmailAddress(_config.Email, _config.Sender), Subject = register.Subject, HtmlContent = register.HtmlContent }; Dictionary <string, string> subs = new Dictionary <string, string> { { "-subject-", "Thank you for Registering" }, { "-fName-", model.FName }, { "-lName-", model.LName }, { "-token-", model.Token.ToString() }, { "-siteUrl-", _siteConfig.SiteUrl } }; msg.AddSubstitutions(subs); msg.AddTo(new EmailAddress(model.To, register.Recipient)); msg.AddBcc(new EmailAddress(_config.Email)); await Send(msg); }
public ActionResult Confirm(Guid id) { try { var registration = _registrationRepository.GetById(id); var eventItem = _eventRepository.GetById(registration.Event.Id); var visitor = _visitorRepository.GetById(registration.Visitor.Id); var ipAddress = GetIPAddress(); // Controleer of in dit event registraties zijn vanaf hetzelfde ip adres bool alreadyRegistered = false; var otherRegistrations = _registrationRepository.ListByEventAndIp(eventItem.Id, ipAddress); if (otherRegistrations.Count() > 0) // Er zijn registraties vanaf hetzelfe IP { foreach (var otherRegistration in otherRegistrations) { if (otherRegistration.Confirmed) { registration.RejectionReason = "Al geregistreerd (IP)"; _registrationRepository.Update(registration); // Dit was dezelfde bezoeker, dus pas dit aan visitor = otherRegistration.Visitor; alreadyRegistered = true; break; } } } if (!alreadyRegistered) { // Controleer of in dit event registraties zijn vanaf hetzelde email adres otherRegistrations = _registrationRepository.GetByVisitorAndEvent(visitor.Id, eventItem); if (otherRegistrations.Count() > 0) // Er zijn registraties vanaf hetzelfe E-mail adres { foreach (var otherRegistration in otherRegistrations) { if (otherRegistration.Confirmed) { registration.RejectionReason = "Al geregistreerd (Email)"; _registrationRepository.Update(registration); // Dit was dezelfde bezoeker, dus pas dit aan visitor = otherRegistration.Visitor; alreadyRegistered = true; break; } } } } // Controleer of de registratie buiten het termijn valt bool earlierRegistered = false; if (!alreadyRegistered) { var registrations = _registrationRepository.GetByVisitorAndNotEvent(visitor.Id, eventItem); if (registrations.Count() > 0) { DateTime legacyDate = eventItem.TimeRange.Start; switch (_settings.LegacyPeriod.Unit) { case Profilan.SharedKernel.Unit.Hours: legacyDate = eventItem.TimeRange.Start.AddHours(-1 * _settings.LegacyPeriod.Amount); break; case Profilan.SharedKernel.Unit.Minutes: legacyDate = eventItem.TimeRange.Start.AddMinutes(-1 * _settings.LegacyPeriod.Amount); break; case Profilan.SharedKernel.Unit.Seconds: legacyDate = eventItem.TimeRange.Start.AddSeconds(-1 * _settings.LegacyPeriod.Amount); break; case Profilan.SharedKernel.Unit.Days: legacyDate = eventItem.TimeRange.Start.AddDays(-1 * _settings.LegacyPeriod.Amount); break; case Profilan.SharedKernel.Unit.Months: legacyDate = eventItem.TimeRange.Start.AddMonths(-1 * _settings.LegacyPeriod.Amount); break; case Profilan.SharedKernel.Unit.Years: legacyDate = eventItem.TimeRange.Start.AddYears(-1 * _settings.LegacyPeriod.Amount); break; default: break; } // Haal de bezochte registraties op (bezocht of bevestigd?) var visitedRegistrations = _registrationRepository.GetVisitedByVisitor(visitor.Id); if (visitedRegistrations.Count() > 0) { var lastVisitedRegistration = visitedRegistrations.Last(); var lastEvent = _eventRepository.GetById(lastVisitedRegistration.Event.Id); if (lastEvent.TimeRange.Start >= legacyDate) { // Update de registratie met de reden van afwijzing lastVisitedRegistration.RejectionReason = "Eerder geregistreerd (E-mail)"; _registrationRepository.Update(lastVisitedRegistration); earlierRegistered = true; } } } } if (earlierRegistered) { return(RedirectToAction("EarlyRegistered")); } if (alreadyRegistered) { return(RedirectToAction("AlreadyRegistered")); } registration.Confirmed = true; registration.ConfirmationDate = DateTime.Now; _registrationRepository.Update(registration); string themeTitle = ""; if (eventItem.Theme != null) { Theme theme = _themeRepository.GetById(eventItem.Theme.Id); themeTitle = "[" + theme.Title + "]"; } var logoUrl = Request.Url.GetLeftPart(UriPartial.Authority) + "/img"; //var barcodeUrl = Request.Url.GetLeftPart(UriPartial.Authority) + "/fonts/Code39.woff"; //var barcodeUrl = @"https://www.barcodesinc.com/generator/image.php?code=" + registration.Id.ToString().ToUpper() + "&style=197&type=C39&width=590&height=100&xres=1&font=4"; var barcodeUrl = @"https://chart.googleapis.com/chart?chl=" + Uri.EscapeUriString(registration.Id.ToString()) + @"&chs=200x200&cht=qr&chld=H%7C0"; var fileName = eventItem.Id + ".pdf"; var temp = Path.GetTempPath(); var path = Path.Combine(temp, fileName); ConfirmationEmail email = new ConfirmationEmail() { To = visitor.Email, Name = visitor.Name, Date = eventItem.TimeRange.Start.ToString("dd-MM-yyyy"), TimeFrom = eventItem.TimeRange.Start.ToShortTimeString(), TimeTill = eventItem.TimeRange.End.ToShortTimeString(), NumberOfVisitors = registration.NumberOfVisitors, LogoUrl = logoUrl, BarcodeUrl = barcodeUrl, RegistrationId = registration.Id.ToString(), Disclaimer = _settings.EmailDisclaimer, ThemeTitle = themeTitle }; //email.GeneratePDF(path, visitor.Name, eventItem.TimeRange, registration.NumberOfVisitors); //email.Attach(new Attachment(path)); email.Send(); return(RedirectToAction("Confirmed")); } catch (Exception e) { throw new Exception(e.Message); } }
public List <string> GetEmailList() { return(string.IsNullOrWhiteSpace(ConfirmationEmail) ? null : ConfirmationEmail.Split(new[] { ',', ';', ':' }).ToList().Select(t => t.Trim()).ToList()); }