private MailsSendedReport SendMail(IEnumerable <IAdherent> users, MailMessage mailMessage) { var activeAdherentStolon = GetActiveAdherentStolon(); MailsSendedReport report = new MailsSendedReport(); foreach (Adherent user in users) { if (!String.IsNullOrWhiteSpace(user.Email)) { try { AuthMessageSender.SendEmail(activeAdherentStolon.Stolon.Label, user.Email, user.Name, mailMessage.Title, mailMessage.Message); report.MailsSended++; } catch (Exception ex) { DotnetHelper.GetLogger <MailsController>().LogError(ex.ToString()); report.MailsNotSended++; } } } return(report); }
public async Task <IActionResult> Create([Bind("InvoiceNumber,CreatedOn,DebtorID,ExpirationDate,Type")] Invoice invoice, string total, string pids, string amounts) { if (ModelState.IsValid) { await CreateInvoice(invoice, pids, amounts, total); //SEND MAIL TO DEBTOR NOTIFYING ABOUT INVOICE if (invoice.Type == "Final") { Debtor debtor = _context.Debtors.Single(s => s.DebtorID == invoice.DebtorID); AuthMessageSender email = new AuthMessageSender(); await email.SendInvoiceEmailAsync(debtor.Email); } return(RedirectToAction("Index")); } var products = _context.Products .Select(s => new SelectListItem { Value = s.ProductID.ToString() + "_" + s.Price.ToString(), Text = s.Name }); ViewBag.Products = new SelectList(products, "Value", "Text", pids); ViewData["DebtorID"] = new SelectList(_context.Debtors, "DebtorID", "FullName", invoice.DebtorID); return(View(invoice)); }
public async Task <IActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { UserApp user = new UserApp() { Email = model.Email, UserName = model.Username, Country = model.Country }; user.Token = TokenGenerator.Generate(); var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { await _signInManager.SignInAsync(user, false); AuthMessageSender sender = new AuthMessageSender(); string baseUrl = $"{this.Request.Scheme}://{this.Request.Host}/"; string url = baseUrl + "EmailConfirmed/" + user.Token; string message = EmailMessageGenerator.GenerateEmailConfirmMessage(url); sender.SendEmailAsync(user.Email, "Please confirm your email", message); return(Redirect(baseUrl)); } else { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } } return(View(model)); }
public async Task <IActionResult> Edit(int id, [Bind("InvoiceNumber,CreatedOn,DebtorID,ExpirationDate,Type")] Invoice invoice, string pids, string amounts, string total) { if (id != invoice.InvoiceNumber) { return(NotFound()); } if (ModelState.IsValid) { Invoice invoiceBeforeUpdate = _context.Invoices.Single(s => s.InvoiceNumber == invoice.InvoiceNumber); await UpdateInvoice(invoice, pids, amounts, total); //SEND MAIL TO DEBTOR NOTIFYING ABOUT INVOICE if (invoice.Type == "Final" && invoiceBeforeUpdate.Type != "Final") { Debtor debtor = _context.Debtors.Single(s => s.DebtorID == invoice.DebtorID); AuthMessageSender email = new AuthMessageSender(); await email.SendInvoiceEmailAsync(debtor.Email); } return(RedirectToAction("Index")); } ViewData["DebtorID"] = new SelectList(_context.Debtors, "DebtorID", "FullName", invoice.DebtorID); return(View(invoice)); }
public async Task <IActionResult> ForgotPassword(ForgotPasswordViewModel model) { if (!ModelState.IsValid) { return(View(model)); } Adherent stolonsUser = _context.Adherents.FirstOrDefault(x => model.Email.Equals(x.Email, StringComparison.CurrentCultureIgnoreCase)); if (stolonsUser == null) { return(View("ForgotPasswordConfirmation")); } ApplicationUser appUser = await _userManager.FindByEmailAsync(stolonsUser.Email.ToString()); string resetPasswordToken = await _userManager.GeneratePasswordResetTokenAsync(appUser); resetPasswordToken = System.Net.WebUtility.UrlEncode(resetPasswordToken); string link = "http://" + Configurations.SiteUrl + "/Account/ResetPassword?token=" + resetPasswordToken + "&mail=" + stolonsUser.Email; //Send mail ForgotPasswordEmailViewModel vmodel = new ForgotPasswordEmailViewModel(stolonsUser, link); AuthMessageSender.SendEmail(Configurations.Application.StolonsLabel, stolonsUser.Email, stolonsUser.Name, "Stolons: Oubli de votre mot de passe", base.RenderPartialViewToString("ResetPasswordEmailTemplate", vmodel), null, null); return(View("ForgotPasswordConfirmation")); }
private async Task CreateLogin(Debtor debtor) { try { User user = new User(); user.AccountType = "Client"; user.Address = debtor.Address; user.PostalCode = debtor.PostalCode; user.City = debtor.City; user.Country = debtor.Country; user.FirstName = debtor.FirstName; user.LastName = debtor.LastName; user.Email = debtor.Email; user.Password = debtor.FirstName + "_" + DateTime.Now.ToString("ddMMHH"); _context.User.Add(user); await _context.SaveChangesAsync(); AuthMessageSender email = new AuthMessageSender(); await email.SendUserEmailAsync(user.Email, user.Password); } catch (Exception ex) { Debug.WriteLine(ex); } }
public async Task <IActionResult> ChangePassword(ChangePasswordViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var user = await GetCurrentAppUserAsync(); if (user != null) { var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent : false); AuthMessageSender.SendEmail(GetCurrentStolon().Label, user.Email, user.Email, "Confirmation de changement de mot de passe", "<h3>Confirmation du changement de mot de passe :</h3><p> Nouveau mot de passe : " + model.NewPassword + "</p>"); return(RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangePasswordSuccess })); } AddErrors(result); return(View(model)); } return(RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error })); }
private async Task SendEmail(ApplicationUser user, List <Ticket> tickets, PredsGame game) { emailSecret = Configuration["EmailSecrets:Email"]; password = Configuration["EmailSecrets:Password"]; EmailSettings es = new EmailSettings() { PrimaryDomain = "smtp.gmail.com", PrimaryPort = 587, SecondayDomain = "smtp.gmail.com", SecondaryPort = 587, UsernameEmail = emailSecret, UsernamePassword = password, FromEmail = "*****@*****.**", ToEmail = user.Email }; string email = user.Email; string title = "7Element Tickets"; string body = $"<h2>Dear {user.FirstName} {user.LastName},</h2><br>" + $"<p>Congrats you have won {tickets.Count} tickets:</p><br><ol>"; for (int i = 0; i < tickets.Count; i++) { body += $"<li>Section {tickets[i].Section} Row {tickets[i].Row} Seat {tickets[i].Seat}</li>"; } body += $"</ol><p>For the Nashville Predators game on the {game.DateTime} vs the {game.Opponent}. </p><br>" + "<h3>Thank you,</h3>" + "<h2>7Element</h2>"; AuthMessageSender ams = new AuthMessageSender(Options.Create(es)); await ams.SendEmailAsync(email, title, body); }
public async Task <IActionResult> Create(DonatedTicketsCreateViewModel dtcvm) { ModelState.Remove("DonatedTickets.UserId"); ModelState.Remove("DonatedTickets.User"); ModelState.Remove("DonatedTickets.PredsGame"); for (int i = 0; i < dtcvm.Tickets.Count; i++) { ModelState.Remove($"Tickets[{i}].DonatedTickets"); } if (ModelState.IsValid) { var user = await _userManager.GetUserAsync(HttpContext.User); dtcvm.DonatedTickets.User = user; dtcvm.DonatedTickets.UserId = user.Id; _context.Add(dtcvm.DonatedTickets); await _context.SaveChangesAsync(); foreach (var ticket in dtcvm.Tickets) { ticket.DonatedTicketsId = dtcvm.DonatedTickets.DonatedTicketsId; _context.Add(ticket); } await _context.SaveChangesAsync(); emailSecret = Configuration["EmailSecrets:Email"]; password = Configuration["EmailSecrets:Password"]; EmailSettings es = new EmailSettings() { PrimaryDomain = "smtp.gmail.com", PrimaryPort = 587, SecondayDomain = "smtp.gmail.com", SecondaryPort = 587, UsernameEmail = emailSecret, UsernamePassword = password, FromEmail = "*****@*****.**", ToEmail = user.Email }; string email = user.Email; string title = "7Element Donation"; string body = $"<h2>Dear {user.FirstName} {user.LastName},</h2><br>" + $"<p>This email is to confirm your desired donation to for the following {dtcvm.NumberOfTickets} tickets:</p><br><ol>"; for (int i = 0; i < dtcvm.Tickets.Count; i++) { body += $"<li>Section {dtcvm.Tickets[i].Section} Row {dtcvm.Tickets[i].Row} Seat {dtcvm.Tickets[i].Seat}</li>"; } body += "</ol><p>To complete your donation please dontate the tickets to tickemaster with the username [email protected].</p><br>" + "<h3>Thank you,</h3>" + "<h2>7Element</h2>"; AuthMessageSender ams = new AuthMessageSender(Options.Create(es)); await ams.SendEmailAsync(email, title, body); return(RedirectToAction(nameof(Confirmation))); } ViewData["PredsGameId"] = new SelectList(_context.PredsGame, "PredsGameId", "PredsGameId", dtcvm.DonatedTickets.PredsGameId); return(View()); }
public IndexModel( UserManager <UsuarioADE> userManager, SignInManager <UsuarioADE> signInManager, AuthMessageSender emailSender) { _userManager = userManager; _signInManager = signInManager; _emailSender = emailSender; }
public async Task <ActionResult> SendTestMail(SendEMailViewModel model) { var message = await EMailTemplate("WelcomeEmail"); message = message.Replace("@ViewBag.Name", CultureInfo.CurrentCulture.TextInfo.ToTitleCase(model.FirstName)); AuthMessageSender sender = new AuthMessageSender(_hostingEnvironment); await sender.SendEmailAsync(model.Email, "Welcome!", message); return(View("ConfirmationEmailSent")); }
public async Task InvokeSendSmsAsyncWithTheCorrectQueueNameAndMessage() { const string phoneNumber = "*****@*****.**"; const string smsMesssage = "test message body"; var mediator = MockIMediator(); var queueStorageService = new Mock <IQueueStorageService>(); var messageSender = new AuthMessageSender(mediator.Object, queueStorageService.Object); await messageSender.SendSmsAsync(phoneNumber, smsMesssage); queueStorageService.Verify(x => x.SendMessageAsync(QueueStorageService.Queues.SmsQueue, @"{""Recipient"":""*****@*****.**"",""Message"":""test message body""}")); }
public ControleUsuariosController( IHostingEnvironment hostingEnvironment, UserManager <UsuarioADE> userManager, SignInManager <UsuarioADE> signInManager, AuthMessageSender emailSender, ApplicationDbContext context ) : base(unitOfWork = new UnitOfWork(context), userManager, signInManager, new ServicoRequisitoUsuario(ref unitOfWork)) { this.context = context; this._emailSender = emailSender; this._servicoLogAcoesEspeciais = new ServicoLogAcoesEspeciais(ref unitOfWork); this._servicoHistoricoGeracaoDocumento = new ServicoHistoricoGeracaoDocumento(ref unitOfWork); this._servicoAlteracoes = new ServicoAlteracaoEntidadesSistema(ref unitOfWork); this._servicoCurso = new ServicoCurso(ref unitOfWork); TemplatePathHelper = new TemplatePathHelper(hostingEnvironment.WebRootPath); }
private static void GenerateOrderPdfAndSendEmail(ProducerBill bill) { try { if (bill.BillEntries.Count == 0) { AuthMessageSender.SendEmail(bill.AdherentStolon.Stolon.Label, bill.AdherentStolon.Adherent.Email, bill.AdherentStolon.Adherent.CompanyName, "Aucune commande chez " + bill.AdherentStolon.Stolon.Label + " cette semaine.", "<h3>Aucune commande chez " + bill.AdherentStolon.Stolon.Label + " cette semaine."); } else { //Generate pdf file bool hasFile = GenerateOrderPDF(bill); //Send mail to producer try { string message = bill.HtmlOrderContent; if (hasFile) { message += "<h3>En pièce jointe votre bon de commande de la semaine chez " + bill.AdherentStolon.Stolon.Label + " (Bon de commande " + bill.BillNumber + ")</h3>"; } AuthMessageSender.SendEmail(bill.AdherentStolon.Stolon.Label, bill.AdherentStolon.Adherent.Email, bill.AdherentStolon.Adherent.CompanyName, "Votre bon de commande de la semaine chez " + bill.AdherentStolon.Stolon.Label + " (Bon de commande " + bill.BillNumber + ")", message, hasFile ? File.ReadAllBytes(bill.GetOrderFilePath()) : null, "Bon de commande " + bill.GetOrderFileName()); } catch (Exception exept) { Logger.LogError("Error on sending mail " + exept); } } } catch (Exception exept) { AuthMessageSender.SendEmail(bill.AdherentStolon.Stolon.Label, Configurations.Application.ContactMailAddress, "Stolons", "Erreur lors de la génération de la facture " + bill.BillNumber + " à " + bill.AdherentStolon.Adherent.Email, "Message d'erreur : " + exept.Message); } }
public SnaBaseController( ApplicationDbContext context, IConfiguration configuration, RoleManager <IdentityRole> roleManager, IAmazonSimpleEmailService client, UserManager <IdentityUser> userManager, SignInManager <IdentityUser> signInManager ) { _configuration = configuration; _roleManager = roleManager; _userManager = userManager; _context = context; _signInManager = signInManager; _AuthMessageSender = new AuthMessageSender(client, _configuration); _appData = new AppDataService(_configuration); }
public void SendSmsAsyncShouldPutCommandOnBus() { const string smsRecipient = "*****@*****.**"; const string smsMesssage = "test message body"; var bus = MockIMediator(); var messageSender = new AuthMessageSender(bus.Object); messageSender.SendSmsAsync(smsRecipient, smsMesssage); bus.Verify(mock => mock.Send( It.Is <NotifyVolunteersCommand>(request => request.ViewModel.SmsMessage == smsMesssage && request.ViewModel.SmsRecipients.SequenceEqual(new List <string> { smsRecipient }))), Times.Exactly(1)); }
public async Task MyMethodAsync() { var eEmailSettings = new EmailSettings() { CcEmail = "", FromEmail = "", PrimaryDomain = "smtp.gmail.com", PrimaryPort = 587, SecondaryPort = 0, SecondayDomain = "", ToEmail = "*****@*****.**", UsernameEmail = SenderEmail, UsernamePassword = SenderPassword }; var emailSender = new AuthMessageSender(eEmailSettings); await emailSender.SendEmailAsync("", "Result file for job ", "Please see attached file.", null); }
public async Task <IActionResult> Edit(int id, [Bind("InvoiceNumber,CreatedOn,DebtorID,CompanyID,Paid,ExpirationDate,Type,Discount,Comments")] Invoice invoice, string pids, string amounts, string total) { if (id != invoice.InvoiceNumber) { return(NotFound()); } if (ModelState.IsValid) { //Update invoice Invoice invoiceBeforeUpdate = _context.Invoices.Single(s => s.InvoiceNumber == invoice.InvoiceNumber); await UpdateInvoice(invoice, pids, amounts, total); //Send email to debtor about new invoice if (invoice.Type == "Final" && invoiceBeforeUpdate.Type != "Final" && !String.IsNullOrEmpty(invoice.DebtorID.ToString())) { Debtor debtor = _context.Debtors.Single(s => s.DebtorID == invoice.DebtorID); AuthMessageSender email = new AuthMessageSender(_settings); await email.SendInvoiceEmailAsync(debtor.Email); } else if (invoice.Type == "Final" && invoiceBeforeUpdate.Type != "Final" && String.IsNullOrEmpty(invoice.CompanyID.ToString())) { Company company = _context.Companies.Single(s => s.CompanyID == invoice.CompanyID); AuthMessageSender email = new AuthMessageSender(_settings); await email.SendInvoiceEmailAsync(company.Email); } return(RedirectToAction("Index")); } //Create selectlist with all companies var companies = _context.Companies .Select(s => new SelectListItem { Value = s.CompanyID.ToString(), Text = s.CompanyName.ToString() + " in " + s.City.ToString() }); //Viewbags and viewdata ViewData["CompanyID"] = new SelectList(companies, "Value", "Text", invoice.CompanyID); ViewData["DebtorID"] = new SelectList(_context.Debtors, "DebtorID", "FullName", invoice.DebtorID); return(View(invoice)); }
public AccountController(UserManager <UsuarioADE> userManager, SignInManager <UsuarioADE> signInManager, IHostingEnvironment hostingEnvironment, AuthMessageSender emailSender, ApplicationDbContext context ) : base(new UnitOfWork(context), userManager, signInManager, new ServicoRequisitoUsuario(ref unitOfWork)) { _hostingEnvironment = hostingEnvironment; _emailSender = emailSender; this.signInManager = signInManager; unitOfWork = new UnitOfWork(context); _servicoInstituicao = new ServicoInstituicao(ref unitOfWork); _servicoCurso = new ServicoCurso(ref unitOfWork); _servicoAreaEstagio = new ServicoAreaEstagioCurso(ref unitOfWork); _servicoRequisito = new ServicoRequisito(ref unitOfWork); _servicoRequisitosDeUsuario = new ServicoRequisitoUsuario(ref unitOfWork); TemplatePathHelper = new TemplatePathHelper(hostingEnvironment.WebRootPath); }
private static void GenerateOrderPdfAndSendEmail(ConsumerBill bill) { try { //Generate pdf file bool hasFile = GenerateBillPDF(bill); //Send mail to consumer string message = "<h3>" + bill.AdherentStolon.Stolon.OrderDeliveryMessage + "</h3>"; message += "<br/>"; message += "<h4>Votre comande de la semaine (Commande " + bill.BillNumber + ")" + ")</h4>"; message += bill.HtmlBillContent; if (hasFile) { message += "<br/><h4>Retrouver aussi en pièce jointe votre commande de la semaine (Commande " + bill.BillNumber + ")</h4>"; } if (bill.AdherentStolon.Token > 0) { message += "<p>Vous avez " + bill.AdherentStolon.Token + "Ṩ, pensez à payer avec vos stols lors de la récupération de votre commande.</p>"; } try { AuthMessageSender.SendEmail(bill.AdherentStolon.Stolon.Label, bill.AdherentStolon.Adherent.Email, bill.AdherentStolon.Adherent.Name, "Votre commande de la semaine (Commande " + bill.BillNumber + ")", message, hasFile ? File.ReadAllBytes(bill.GetBillFilePath()) : null, "Commande " + bill.GetBillFileName()); } catch (Exception exept) { Logger.LogError("Error on sending mail " + exept); } } catch (Exception exept) { AuthMessageSender.SendEmail(bill.AdherentStolon.Stolon.Label, Configurations.Application.ContactMailAddress, "Stolons", "Erreur lors de la génération de la commande " + bill.BillNumber + " à " + bill.AdherentStolon.Adherent.Email, "Message d'erreur : " + exept.Message); } }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); if (ModelState.IsValid) { var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email }; var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { userId = user.Id, code = code }, protocol: Request.Scheme); AuthMessageSender sender = new AuthMessageSender(); await sender.SendEmailAsync(Input.Email, "Confirm your email", $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); // await _emailSender.SendEmailAsync(Input.Email, "Confirm your email", // $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); await _signInManager.SignInAsync(user, isPersistent : false); var profileId = profileService.CreateProfile(user.Id); user.ProfileId = profileId; userService.AddUserRole(user.Id, "7b7bb137-36a0-42fa-a59c-622e3e209d37"); return(LocalRedirect(returnUrl)); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return(Page()); }
public async Task SendEmailAsyncTest() { var assembly = typeof(Startup).GetTypeInfo().Assembly; var contentRoot = TestHelper.GetProjectPath(assembly); var config = new ConfigurationBuilder() .SetBasePath(contentRoot) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.Development.json", optional: true) .AddUserSecrets <Startup>() .AddEnvironmentVariables() .Build(); var sp = new ServiceCollection() .AddLogging() .Configure <AuthMessageSenderOptions>(config.GetSection("AuthMessageSender")) .AddOptions() .BuildServiceProvider(); var optionsAccessor = sp.GetService <IOptions <AuthMessageSenderOptions> >(); var factory = sp.GetService <ILoggerFactory>(); factory.AddConsole(); ILogger <AuthMessageSender> logger = factory.CreateLogger <AuthMessageSender>(); var cls = new AuthMessageSender(optionsAccessor, logger); // TODO: Replace placeholder code with commented code to test email function when real // email info is available. await Task.Run(() => { }); //var email = "*****@*****.**"; //var subject = "Test"; //var message = "Test"; //try //{ // await cls.SendEmailAsync(email, subject, message); //} //catch (Exception ex) //{ // Assert.Fail(ex.Message); //} }
public void Generate() { EmailSettings appSettings = new EmailSettings() { PrimaryDomain = "smtp.gmail.com", PrimaryPort = 587, SecondayDomain = "smtp.live.com", SecondaryPort = 587, UsernameEmail = "*****@*****.**", UsernamePassword = "******", FromEmail = "*****@*****.**", ToEmail = "*****@*****.**", CcEmail = "" }; IOptions <EmailSettings> options = Options.Create(appSettings); AuthMessageSender mail = new AuthMessageSender(options); mail.SendEmailAsync("*****@*****.**", "Test sender", "Test"); }
public async Task SendNotifyVolunteersCommandWhenInvokingSendEmailAsync() { const string emailRecipient = "*****@*****.**"; const string emailSubject = "test subject"; const string emailMessage = "test message body"; var mediator = MockIMediator(); var messageSender = new AuthMessageSender(mediator.Object, Mock.Of <IQueueStorageService>()); await messageSender.SendEmailAsync(emailRecipient, emailSubject, emailMessage); mediator.Verify(mock => mock.SendAsync( It.Is <NotifyVolunteersCommand>(request => request.ViewModel.EmailMessage == emailMessage && request.ViewModel.EmailRecipients.SequenceEqual(new List <string> { emailRecipient }) && request.ViewModel.HtmlMessage == emailMessage && request.ViewModel.Subject == emailSubject)), Times.Exactly(1)); }
public void SendEmailAsyncShouldPutCommandOnBus() { const string emailRecipient = "*****@*****.**"; const string emailSubject = "test subject"; const string emailMessage = "test message body"; var bus = MockIMediator(); var messageSender = new AuthMessageSender(bus.Object); messageSender.SendEmailAsync(emailRecipient, emailSubject, emailMessage); bus.Verify(mock => mock.Send( It.Is <NotifyVolunteersCommand>(request => request.ViewModel.EmailMessage == emailMessage && request.ViewModel.EmailRecipients.SequenceEqual(new List <string> { emailRecipient }) && request.ViewModel.HtmlMessage == emailMessage && request.ViewModel.Subject == emailSubject)), Times.Exactly(1)); }
public async Task SendEmail(string actionName, string controllerName, ApplicationUser user, string email, string emailTemplate, string emailSubject) { string code = null; if (codeType == "EmailConfirmation") { code = await _userManager.GenerateEmailConfirmationTokenAsync(user); } else if (codeType == "ResetPassword") { code = await _userManager.GeneratePasswordResetTokenAsync(user); } var callbackUrl = Url.Action(actionName, controllerName, new { userId = user.Id, date = DateTime.Now, code = code }, protocol: Context.Request.Scheme); var message = await EMailTemplate(emailTemplate); message = message.Replace("@ViewBag.Name", CultureInfo.CurrentCulture.TextInfo.ToTitleCase(user.FirstName)); message = message.Replace("@ViewBag.Link", callbackUrl); AuthMessageSender sender = new AuthMessageSender(_hostingEnvironment); await sender.SendEmailAsync(email, emailSubject, message); }
public bool UpdateBillCorrection(VmBillCorrection billCorrection) { billCorrection.Reason = "Modification le : " + DateTime.Now.ToString() + "\n\rRaison : " + billCorrection.Reason + "\n\r\n\r"; ProducerBill bill = _context.ProducerBills.Include(x => x.BillEntries).Include(x => x.AdherentStolon).First(x => x.BillId == billCorrection.ProducerBillId); bill.ModificationReason = billCorrection.Reason; bill.HasBeenModified = true; List <Guid?> modifiedBills = new List <Guid?>(); foreach (var billQuantity in billCorrection.NewQuantities) { var billEntry = bill.BillEntries.First(x => x.Id == billQuantity.BillId); billEntry.Quantity = billQuantity.Quantity; billEntry.HasBeenModified = true; if (!modifiedBills.Any(x => x == billEntry.ConsumerBillId)) { modifiedBills.Add(billEntry.ConsumerBillId); } } _context.SaveChanges(); bill = _context.ProducerBills.Include(x => x.BillEntries).Include(x => x.AdherentStolon).Include(x => x.AdherentStolon.Stolon).Include(x => x.AdherentStolon.Adherent).First(x => x.BillId == billCorrection.ProducerBillId); bill.BillEntries.ForEach(x => x.ProductStock = _context.ProductsStocks.Include(y => y.Product).First(stock => stock.Id == x.ProductStockId)); bill.HtmlBillContent = BillGenerator.GenerateHtmlBillContent(bill, _context); BillGenerator.GenerateBillPDF(bill); foreach (var billId in modifiedBills) { var billToModify = _context.ConsumerBills.Include(x => x.AdherentStolon.Adherent).First(x => x.BillId == billId); billToModify.ModificationReason += billCorrection.Reason; billToModify.HasBeenModified = true; //Envoie mail user BillGenerator.GenerateBillPDF(billToModify); AuthMessageSender.SendEmail(billToModify.AdherentStolon.Stolon.Label, billToModify.AdherentStolon.Adherent.Email, billToModify.AdherentStolon.Adherent.CompanyName, "Votre bon de commande de la semaine chez " + billToModify.AdherentStolon.Stolon.Label + "a été modifié (Bon de commande " + bill.BillNumber + ")", "Oops, petit problème, malheureusement tout vos produits ne pourront pas être disponible. Votre commande a été modifié. En voici la raison : " + billCorrection.Reason + "\n\n" + bill.HtmlBillContent); } _context.SaveChanges(); return(true); }
//Create new login for debtor private async Task CreateLogin(Debtor debtor) { try { User user = new User(); user.Debtor = debtor; user.Email = debtor.Email; user.Password = debtor.FirstName + "_" + DateTime.Now.ToString("ddMMHH"); //Encrypt password string hash = encryption.Encrypt(user.Password); user.Password = hash; _context.Users.Add(user); await _context.SaveChangesAsync(); //Send email with username and password AuthMessageSender email = new AuthMessageSender(_settings); await email.SendLoginEmailAsync(user.Email, encryption.Decrypt(user.Password)); } catch (Exception ex) { Debug.WriteLine(ex); } }
private static void TriggerOrderMode(Stolon stolon, ApplicationDbContext dbContext) { foreach (ProductStockStolon productStock in dbContext.ProductsStocks.Include(x => x.AdherentStolon).Include(x => x.Product).Where(x => x.AdherentStolon.StolonId == stolon.Id).ToList()) { if (productStock.State == ProductState.Stock) { productStock.State = ProductState.Disabled; } } dbContext.SaveChanges(); //Send email to all adherent that have subscribe to product by mail string htmlMessage = "Bonjour, les commandes sont ouverte chez " + stolon.Label + ". Vous pouvez dès maintenant et jusqu'à " + stolon.DeliveryAndStockUpdateDayStartDate.ToFrench() + " " + stolon.DeliveryAndStockUpdateDayStartDateHourStartDate + ":" + stolon.DeliveryAndStockUpdateDayStartDateMinuteStartDate + " commander vos produits sur " + Configurations.Application.StolonsUrl; //TODO générer un jolie message avec la liste des produits foreach (var adherentStolon in dbContext.AdherentStolons.Include(x => x.Adherent).Where(x => x.StolonId == stolon.Id && x.Adherent.ReceivedProductListByEmail).AsNoTracking()) { AuthMessageSender.SendEmail(stolon.Label, adherentStolon.Adherent.Email, adherentStolon.Adherent.Name + " " + adherentStolon.Adherent.Surname, "Commande ouverte chez " + stolon.Label, htmlMessage); } }
public ActionResult ForgotPassword(LostPasswordModel model) { //Boolean ErrorFlag = false; //unused if (TryValidateModel(model)) { var messageService = new AuthMessageSender(); var userService = new User.UserService(); var newPassword = userService.ResetUserPassword(model.Email); var sentmessage = messageService.SendEmailAsync(model.Email, "Reset IRIS Password", "Hello " + model.Email + " your temporary password is " + newPassword); if (!sentmessage) { //ErrorFlag = true; ModelState.AddModelError(string.Empty, "SMTP server is down, unable to send temporary password at this time."); return(View("ForgotPassword", model)); } else { Session["ExpirationTime"] = DateTime.Now.AddHours(4); return(View("ForgotPasswordConfirmation")); } //return RedirectToAction("ForgotPasswordConfirmation"); //unreachable } else { return(View("Login")); } }