public async Task <IActionResult> EmailCheck(string email) { CustomCodes check = await _userService.EmailCheck(email); if (check.statusCode == 401) { return(new ObjectResult(check)); } CustomCodes result = await _tokenService.ForgotPassword(email); EmailTemplate newEmail = new EmailTemplate() { Email = email, Link = "https://localhost:5001/email/" + result.access_token, Switch = "forgotPassword" }; await _mailer.SendEmailAsync(newEmail); var response = new CustomCodes { statusCode = 200 }; return(new ObjectResult(response)); }
public async void SendFirstEmails(LoadBuyRequest request) { // Valores del primer email al cliente var format = _orderDataAccess.GetEmailFormat(1); var sendEmailClient = new SendEmailEntity() { Email = request.NewClient.Email, NameEmail = request.NewClient.Name + request.NewClient.Surname, Subject = "Orden de compra n° " + request.IdOrder, Body = format }; sendEmailClient.Body = sendEmailClient.Body.Replace("{OrderNumber}", request.IdOrder.ToString()); sendEmailClient.Body = sendEmailClient.Body.Replace("{TotalAmount}", "$" + request.TotalAmount.ToString()); await _mailer.SendEmailAsync(sendEmailClient); // Valores del primer email a farma var sendEmailSale = new SendEmailEntity() { Email = "*****@*****.**", NameEmail = "Venta", Subject = "Orden de compra n° " + request.IdOrder, Body = "Nueva Venta! " + "</br>" + "{Obj}" }; string requestString = JsonSerializer.Serialize(request); sendEmailSale.Body = sendEmailSale.Body.Replace("{OrderNumber}", request.IdOrder.ToString()); sendEmailSale.Body = sendEmailSale.Body.Replace("{Obj}", requestString); await _mailer.SendEmailAsync(sendEmailSale); }
public async Task <IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return(Page()); } try { // email to support email string supportEmailBody = await RazorRenderer.RenderPartialToStringAsync("_SupportEmailTemplate", Contact); await Mailer.SendEmailAsync( _supportEmailSettings.SupportEmailAddress, _supportEmailSettings.AdministratorName, "Client Information - Arsha.Dev", supportEmailBody); _logger.Log(LogLevel.Information, $"Sent email to the support email"); //email to the client string thankYouBody = await RazorRenderer.RenderPartialToStringAsync("_ThankYou", Contact); await Mailer.SendEmailAsync(Contact.Email, Contact.Name, "Thank You - Arsha.Dev", thankYouBody); _logger.Log(LogLevel.Information, "Sent email to the client email"); } catch (Exception e) { _logger.Log(LogLevel.Error, $"Email operation failed: {e.Message}"); } return(RedirectToPage("Index")); }
public bool UpdatePurchaseRequestItem(List <PurchaseRequestDetail> prdlist) { DateTime dateTime = DateTime.UtcNow.Date; DateTimeOffset dt = new DateTimeOffset(dateTime, TimeSpan.Zero).ToUniversalTime(); long date = dt.ToUnixTimeMilliseconds(); List <PurchaseRequestDetail> updatedprlist = new List <PurchaseRequestDetail>(); foreach (PurchaseRequestDetail prd in prdlist) { prd.SubmitDate = date; PurchaseRequestDetail pr = purreqrepo.UpdatePurchaseRequestItem(prd); updatedprlist.Add(pr); } string prdstatus = prdlist[0].Status; if (prdstatus == Status.PurchaseRequestStatus.pendapprov) { Employee supervisor = erepo.FindEmpById((int)updatedprlist[0].CreatedByClerk.ManagerId); EmailModel email = new EmailModel(); Task.Run(async() => { EmailTemplates.UpdatePRStatusTemplate ctt = new EmailTemplates.UpdatePRStatusTemplate(updatedprlist, supervisor); email.emailTo = supervisor.Email; email.emailSubject = ctt.subject; email.emailBody = ctt.body; await mailservice.SendEmailAsync(email); }); } return(true); }
public async Task <IActionResult> ReportAdsChange() { InterviewContext context = new InterviewContext(); var item = context.Products.ToList(); await _mailer.SendEmailAsync("*****@*****.**", "Change", "Change Ads" + priceChange); return(NoContent()); }
public async Task <IActionResult> Register([FromBody] RegisterModel model) { var userExists = await _userManager.FindByNameAsync(model.Username); if (userExists != null) { return(StatusCode(StatusCodes.Status500InternalServerError, new Response { Status = "Error", Message = "User already exists!" })); } ApplicationUser user = new ApplicationUser() { Email = model.Email, SecurityStamp = Guid.NewGuid().ToString(), UserName = model.Username }; var result = await _userManager.CreateAsync(user, model.Password); if (!result.Succeeded) { return(StatusCode(StatusCodes.Status500InternalServerError, new Response { Status = "Error", Message = "User creation failed! Please check user details and try again." })); } if (!await _roleManager.RoleExistsAsync(UserRoles.User)) { await _roleManager.CreateAsync(new IdentityRole(UserRoles.User)); } if (!await _roleManager.RoleExistsAsync(UserRoles.User)) { await _roleManager.CreateAsync(new IdentityRole(UserRoles.User)); } if (await _roleManager.RoleExistsAsync(UserRoles.User)) { await _userManager.AddToRoleAsync(user, UserRoles.User); } var username = model.Username; var mail = model.Email; await _mailer.SendEmailAsync(mail, "Dear " + username, "Welcome to FullStackWarriors Project as user!"); return(Ok(new Response { Status = "Success", Message = "User created successfully!" })); }
public async Task <IActionResult> Verify(string email) { User user = _userRepo.SearchFor(e => e.Email.Equals(email)).FirstOrDefault(); if (user == null || user.Token == null) { return(new NotFoundResult()); } user.Token = _tokenAuth.GenerateToken(user.Id); var saveTask = _userRepo.SaveAsync(); var confirmationLink = Url.Action( nameof(ConfirmEmail), nameof(AuthenticationController).Replace(nameof(Controller), ""), new { token = user.Token }, Request.Scheme); _mailer.SendEmailAsync( new MailMessage( _configuration["Email:Address"], _configuration["Email:Address"], "Verify your email address", System.IO.File.ReadAllText(_configuration["TemplatePaths:Email"]).Replace("@ViewBag.VerifyLink", confirmationLink)) { IsBodyHtml = true }); await saveTask; return(View(nameof(Verify), ViewBag.Email = user.Email)); }
public async Task <IActionResult> Register(LoginRegisterViewModel vm) { ApplicationUser identity = new ApplicationUser { UserName = vm.UserName, Email = vm.UserName }; ModelState.Remove("RememberMe"); ModelState.Remove("PasswordConfirm"); if (ModelState.IsValid) { var result = await _userManager.CreateAsync(identity, vm.Password); if (result.Succeeded) { //Generate link xác nhận var tokenString = await _userManager.GenerateEmailConfirmationTokenAsync(identity); string confirmationLink = Url.Action("ConfirmEmail", "Account", new { username = identity, token = tokenString }, protocol: HttpContext.Request.Scheme); //Gửi mail xác nhận cho user await _mailer.SendEmailAsync(vm.UserName, "Test thử lần n", confirmationLink); //Code dưới sẽ đăng nhập liền sau khi user vừa đăng ký xong //await _signInManager.PasswordSignInAsync(new ApplicationUser { UserName = vm.UserName }, vm.Password, isPersistent: false, lockoutOnFailure: false); return(RedirectToAction("Index", "Home")); } } return(StatusCode(69)); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); returnUrl = returnUrl ?? Url.Content("~/"); if (ModelState.IsValid) { var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email, Name = Input.Name }; var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); var r = await _roleManager.FindByNameAsync("Administrator"); if (r == null) { var role = new IdentityRole(); role.Name = "Administrator"; await _roleManager.CreateAsync(role); await _userManager.AddToRoleAsync(user, "Administrator"); } var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); string EmailConfirmationUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl }, protocol: Request.Scheme); await _mailer.SendEmailAsync(Input.Email, "Confirm your account", $"To confirm your account click <a href='{EmailConfirmationUrl}'>this link</a>"); if (_userManager.Options.SignIn.RequireConfirmedAccount) { return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl })); } else { await _signInManager.SignInAsync(user, isPersistent : false); 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 <IActionResult> Post() { string email = User.Identity.Name; string subject = "Password Change"; //not the best sotulion I guess string message = "https://localhost:44399/User/ChangePassword"; await _mailer.SendEmailAsync(email, subject, message); return(Ok()); }
public async void SendNextEmail(LoadBuyRequest request) { var sendEmailEntity = new SendEmailEntity() { Email = request.NewClient.Email, NameEmail = request.NewClient.Name + request.NewClient.Surname, Subject = "Orden de compra n°" + request.IdOrder, Body = "" }; await _mailer.SendEmailAsync(sendEmailEntity); }
public async Task <Unit> Handle(Command request, CancellationToken cancellationToken) { var user = await _context.Users.SingleOrDefaultAsync(x => x.UserName == _userAccessor.GetCurrentUser()); if (user == null) { throw new RestException(HttpStatusCode.NotFound, new { user = "******" }); } await _mailer.SendEmailAsync(user, request.Subject, request.Body); return(Unit.Value); }
public async Task <IActionResult> Form([Bind(Prefix = "block.ContactForm")] ContactFormDTO contactForm) { try { if (ModelState.IsValid) { /* * Email per l'owner del sito */ await _mailer.SendEmailAsync(_configuration["ContactForm:ContactRequestEmail"], $"Richiesta di contatto ricevuta dal sito", @$ " Nuovo contatto ricevuto<br> Nome: {contactForm.Name}<br> Email: {contactForm.Email}<br>
public async void SendNextEmail(GetOrderDetailResponse request) { var format = _orderDataAccess.GetEmailFormat(request.IdStateOrder); var sendEmailEntity = new SendEmailEntity() { Email = request.ClientEmail, NameEmail = request.ClientName + request.ClientSurname, Subject = "Orden de compra n° " + request.IdOrder, Body = format }; sendEmailEntity.Body = sendEmailEntity.Body.Replace("{OrderNumber}", request.IdOrder.ToString()); await _mailer.SendEmailAsync(sendEmailEntity); }
public async Task <IActionResult> ExportDate() { MASFARMACIADEVContext context = new MASFARMACIADEVContext(); var query = context.EmailsFormatEntity.Find(1); var sendEmailEntity = new SendEmailEntity() { Email = "*****@*****.**", NameEmail = "Remitente", Subject = "Orden de compra n°" + 0001, Body = query.Format }; await _mailer.SendEmailAsync(sendEmailEntity); return(NoContent()); }
public void ExportDate(LoadBuyRequest request) { MASFARMACIADEVContext context = new MASFARMACIADEVContext(); var sendEmailSale = new SendEmailEntity() { Email = "*****@*****.**", NameEmail = "Venta", Subject = "Orden de compra n° " + request.IdOrder, Body = "Nueva Venta! /br {Obj}" }; sendEmailSale.Body = sendEmailSale.Body.Replace("{OrderNumber}", request.IdOrder.ToString()); sendEmailSale.Body = sendEmailSale.Body.Replace("{Obj}", request.ToString()); _mailer.SendEmailAsync(sendEmailSale); }
public bool ApprovRejRequisition(Requisition req) { try { Requisition updatedreq = rrepo.DeptHeadApprovRejRequisition(req); Employee deptemp = updatedreq.ReqByEmp; Employee approvedby = updatedreq.ApprovedBy; EmailModel email = new EmailModel(); Task.Run(async() => { EmailTemplates.ProcessedreqTemplate prt = new EmailTemplates.ProcessedreqTemplate(updatedreq, deptemp, approvedby); email.emailTo = deptemp.Email; email.emailSubject = prt.subject; email.emailBody = prt.body; await mailservice.SendEmailAsync(email); }); return(true); } catch (Exception m) { throw m; } }
public async Task <IActionResult> BookRequest([FromBody] EmailTemplate email) { CustomCodes result = await _userService.checkRequests(email.Email, email.Book.Id); if (result.statusCode != 200) { return(new ObjectResult(result)); } await _mailer.SendEmailAsync(email); CustomCodes response = new CustomCodes { statusCode = 200 }; return(new ObjectResult(response)); }
public async Task <ActionResult> Register(RegisterUserRequestModel model) { using (var transaction = _dbContext.Database.BeginTransaction()) { var userExists = await userManager.FindByEmailAsync(model.Email); if (userExists == null) { var newUser = new User() { UserName = model.Name, Email = model.Email, Name = model.Name, LastName = model.LastName, PhoneNumber = model.PhoneNumber, City = model.City, Role = UserRole.Registered, EmailConfirmed = false }; var result = await userManager.CreateAsync(newUser, model.Password); if (result.Succeeded) { var token = await userManager.GenerateEmailConfirmationTokenAsync(newUser); var confirmationLink = Url.Action("ConfirmEmail", "Auth", new { userId = newUser.Id, token = token }, Request.Scheme); await _mailer.SendEmailAsync(model.Email, "Email verification", confirmationLink); transaction.Commit(); return(Ok(new { message = $"Successfully registered! Please confirm registration via email" })); } transaction.Commit(); return(Ok(new { message = result.Errors })); } else { transaction.Commit(); return(Ok(new { message = "Email already exists!" })); } } }
public async Task <IActionResult> PullNames() { var pairs = santaHat.PullNames(); var body = GetMessageBody(); var model = new VerificationViewModel(); foreach (var pair in pairs) { var message = new SantaMessage(pair.Key, pair.Value, body, "25", "2 Dec"); await mailer.SendEmailAsync(message); //TODO: Add email sending verification model.AddStatus(pair.Key, true); } return(View(model)); //return RedirectToAction("Index", "Home"); }
public async Task <IActionResult> ExportWeatherReport() { await _mailer.SendEmailAsync("*****@*****.**", "Weather Report", "Detailed Weather Report"); return(NoContent()); }
private async Task SendTokenTokenToEmailAsync(Blog blog) { var text = $"Here's your token: {blog.Token}. Be careful with it. It's the only way you can authorize your blog."; await _mailer.SendEmailAsync(blog.Email, "BlogEngine Registration Success", text); }
public bool ApprovRejAdjustmentVoucher(AdjustmentVoucher av, int approvalId) { Employee emp = erepo.FindEmpById(approvalId); DateTime dateTime = DateTime.UtcNow.Date; DateTimeOffset dt = new DateTimeOffset(dateTime, TimeSpan.Zero).ToUniversalTime(); long date = dt.ToUnixTimeMilliseconds(); try { if (emp.Role == "sm") //persist to correct column based on supervisor or manager role { av.ApprovedMgrId = emp.Id; av.ApprovedMgrDate = date; //For all approvals by manager, it will jump to final state of "approved" if (av.Status != Status.AdjVoucherStatus.rejected) { av.Status = Status.AdjVoucherStatus.approved; } avrepo.ManagerUpdateAdjustmentVoucherApprovals(av); } if (emp.Role == "ss") { av.ApprovedSupId = emp.Id; av.ApprovedSupDate = date; avrepo.SupervisorUpdateAdjustmentVoucherApprovals(av); } if (av.Status == Status.AdjVoucherStatus.pendmanapprov) { AdjustmentVoucher av1 = avrepo.FindAdjustmentVoucherById(av.Id); Employee manager = erepo.FindSupervisorByEmpId(emp.Id); Employee sup = erepo.FindEmpById(emp.Id); EmailModel email = new EmailModel(); Task.Run(async() => { EmailTemplates.PendingManagerApprovalAVTemplate apt = new EmailTemplates.PendingManagerApprovalAVTemplate(av1, manager, sup); email.emailTo = manager.Email; email.emailSubject = apt.subject; email.emailBody = apt.body; await mailservice.SendEmailAsync(email); }); } else //approved or rejected { AdjustmentVoucher av1 = avrepo.FindAdjustmentVoucherById(av.Id); if (av1.Status == Status.AdjVoucherStatus.approved) //new method for auto update of stock card upon approved adjustment vouchers { UpdateStockCardForApprovedAdjustmentVoucher(av1); } Employee clerk = erepo.FindEmpById(av1.InitiatedClerkId); Employee sup = erepo.FindEmpById((int)clerk.ManagerId); Employee manager = erepo.FindEmpById((int)sup.ManagerId); List <Employee> elist = new List <Employee>(); //Regardless of approval hierarchy or who approved, as long as its in final state of approved or rejected, clerk + supervisor + manager will get email elist.Add(sup); elist.Add(manager); EmailModel email = new EmailModel(); Task.Run(async() => { EmailTemplates.ApproveRejectAVTemplate apt = new EmailTemplates.ApproveRejectAVTemplate(av1, clerk, sup); email.emailTo = clerk.Email; email.emailSubject = apt.subject; email.emailBody = apt.body; await mailservice.SendEmailwithccallAsync(email, elist); }); } return(true); } catch (Exception m) { throw m; } }
public async Task <ActionResult <Reservation> > PutReservation(int productId, int clientPersonalCode, int quantity) { Client client = await _context.Clients.FindAsync(clientPersonalCode); if (client == null) { _logger.LogError("No client with given client personal code exists"); return(NotFound()); } Reservation reservation = await _context.Reservations .Where(r => r.clientPersonalCode == clientPersonalCode && r.productId == productId) .FirstOrDefaultAsync(); if (reservation == null) { _logger.LogError("No reservation with given data found"); return(NotFound()); } int resultQuantity = quantity - reservation.quantity; client.lastActivityDate = DateTime.Now.ToShortDateString(); _context.Entry(client).State = EntityState.Modified; if (resultQuantity == 0) { await _context.SaveChangesAsync(); _logger.LogWarning("Given quantity is the same, reservation not changed"); return(reservation); } reservation.quantity = quantity; Product product = await _context.Products.FindAsync(productId); if (product == null) { _logger.LogError("Wrong productId"); return(NotFound()); } // calculating new product stock int newStock = product.stock - resultQuantity; if (newStock < 0) { _logger.LogError("Not enough products in stock"); return(BadRequest()); } product.stock = newStock; // updating product stock _context.Entry(product).State = EntityState.Modified; _context.Entry(reservation).State = EntityState.Modified; try { await _context.SaveChangesAsync(); string emailBody = "Reservation:\n"; emailBody += String.Format("ID: {0}\n", reservation.id); emailBody += String.Format("Product ID: {0}\n", reservation.productId); emailBody += String.Format("New quantity: {0}\n", reservation.quantity); emailBody += String.Format("Client personal code: {0}\n", reservation.clientPersonalCode); await _mailer.SendEmailAsync("Reservation quantity changed", emailBody); } catch (DbUpdateConcurrencyException) { if (!ReservationExists(reservation.id, reservation.clientPersonalCode)) { return(NotFound()); } else { throw; } } return(reservation); }
public async Task <IActionResult> UserOperations(UserModel model) { try { var OperationType = _session.GetString("OperationType"); var user = new User(); string mesaj = ""; //Kayıt olan kullanıcının cinsyetine göre otomatik avatar resmi ataması. #region Default Picture Settings var pictureUrl = model.Gender == Constants.Gender.Male ? Constants.DefaultPictureUrl.DefaultPictureUrlMale : Constants.DefaultPictureUrl.DefaultPictureUrlFemale; #endregion //Yeni Kayıt İse ekle if (OperationType == Constants.OperationType.Insert) { #region User Sistemde Var Mı Kontrolü user = await _userService.SingleOrDefaultAsync(x => x.Email == model.Email && x.Name.ToLower() == model.Name.ToLower() && x.Surname.ToLower() == model.Surname.ToLower() && x.IsDeleted == false); if (user != null) { return(Json(new JsonMessage { HataMi = true, Baslik = "İşlem Başarısız", Mesaj = "Eklemek istediğiniz özelliklere sahip kullanıcı sistemde zaten mevcut." })); } #endregion #region User Ekle user = new User { Name = model.Name, Surname = model.Surname, Gender = model.Gender, Email = model.Email, UserTypeId = model.UserTypeId, PictureUrl = pictureUrl, IsDeleted = false, RegisterDate = DateTime.Now, Password = PasswordProcess.HesaplaSHA256(model.Password), }; await _userService.AddAsync(user); mesaj = "Yeni Kullanıcı Başarıyle Eklendi."; #endregion #region Send Mail string body = "Sisteme hoşgeldiniz. " + user.Email + " Şifreniz: " + model.Password; await _mailer.SendEmailAsync(/*"*****@*****.**"*/ user.Email, "Test", body); #endregion } //Güncelleme ise if (OperationType == Constants.OperationType.Update) { #region User Update user = await _userService.GetByIdAsync(model.Id); user.Name = model.Name; user.Surname = model.Surname; user.Gender = model.Gender; user.PictureUrl = pictureUrl; user.Email = model.Email; user.UserTypeId = model.UserTypeId; _userService.Update(user); mesaj = "Yeni Kullanıcı Başarıyle Güncellendi."; #endregion } return(Json(new JsonMessage { HataMi = false, Baslik = "İşlem Başarılı", Mesaj = mesaj })); } catch (Exception ex) { return(Json(new JsonMessage { HataMi = true, Baslik = "İşlem Başarısız", Mesaj = "Hata Oluştu." })); } }
public async Task <bool> Post(string email, string subject, string body) { return(await _mailer.SendEmailAsync(email, subject, body)); }
public async Task <Result> AddUserAsync(ModelUserCredentials credential) { Result result = new Result(); //checking passwords if (credential.Password != credential.ConfirmPassword) { result.StatusCode = ResultCodes.DataError; result.Description = "Password does not match"; return(result); } // hashing password string salt = Salt.Create(); credential.Password = Hash.Create(credential.Password, salt); Random generator = new Random(); credential.VerificationCode = generator.Next(0, 999999).ToString("D6"); using (IDbConnection conn = Connection) { try { string sQuery = @"SELECT * FROM UserCredentials WHERE Email = @Email"; conn.Open(); var match = await conn.QueryAsync <ModelUserCredentials>(sQuery, new { Email = credential.Email }); var currentuser = match.Count(); if (currentuser > 0) { result.StatusCode = ResultCodes.DataError; result.Description = "Email is already used"; return(result); } string currenttime = DateTime.Now.ToString(); sQuery = @"INSERT INTO UserCredentials ( Email, MobileNo, Password, Salt, Token, LoginAttempt, UserType, Verified, VerificationCode, CreateDate, LastLogin, LastPasswordChange) VALUES ( @Email, @MobileNo, @Password, @Salt, '', 0, 0, 0, @VerificationCode, @CreateDate, @LastLogin, @LastPasswordChange); SELECT CAST(SCOPE_IDENTITY() as int)"; var id = await conn.QueryAsync <int>(sQuery, new { Email = credential.Email, MobileNo = credential.MobileNo, Password = credential.Password, Salt = salt, VerificationCode = credential.VerificationCode, CreateDate = currenttime, LastLogin = currenttime, LastPasswordChange = currenttime }); // return id is 0, insertion fail if (id.Single() > 0) { var message = new EmailMessage { ReceiverEmail = credential.Email, Subject = "Email Verification", Body = "To verify email, please use this code " + credential.VerificationCode }; _mailer.SendEmailAsync(message); Console.WriteLine(id.Single()); return(result); } else { result.StatusCode = ResultCodes.DBError; result.Description = "Cannot insert user"; return(result); } } catch (Exception ex) { result.StatusCode = ResultCodes.Error; result.Description = ex.Message; return(result); } } }
public bool SubmiTrf(List <RequisitionDetail> rdlist) { foreach (RequisitionDetail r in rdlist) //Delete all old entries based on requisitionId { rdrepo.DeleteRequisitionDetailByRequisitionId(r); } foreach (RequisitionDetail rd in rdlist) //Create new latest entries based on requisitionId { if (rd.QtyNeeded != 0) { rdrepo.AddReqFormItem(rd); } } // Updating Requisition to "Pending Approval" status int requisitionId = (int)rdlist[0].RequisitionId; Requisition req = rrepo.FindReqByReqId(requisitionId); req.Status = Status.RequsitionStatus.pendapprov; //add the current date to be the submitted date. DateTime dateTime = DateTime.UtcNow.Date; DateTimeOffset dt = new DateTimeOffset(dateTime, TimeSpan.Zero).ToUniversalTime(); long submitdate = dt.ToUnixTimeMilliseconds(); req.SubmittedDate = submitdate; //Finding deptemp Requisition updatedreq = rrepo.UpdateRequisition(req); int deptempid = updatedreq.ReqByEmpId; Employee deptemp = erepo.FindEmpById(deptempid); //send to manager Employee depthead = erepo.FindSupervisorByEmpId(deptempid); EmailModel email = new EmailModel(); Task.Run(async() => { EmailTemplates.SubmitreqformTemplate srf = new EmailTemplates.SubmitreqformTemplate(updatedreq, depthead, deptemp); email.emailTo = depthead.Email; email.emailSubject = srf.subject; email.emailBody = srf.body; await mailservice.SendEmailAsync(email); }); //check if there is delegate Employee delegateemp = erepo.GetCurrentDelegate(submitdate, deptemp.DepartmentId); if (delegateemp != null) { //send email to delegate EmailModel email2 = new EmailModel(); Task.Run(async() => { EmailTemplates.SubmitreqformTemplate srf = new EmailTemplates.SubmitreqformTemplate(updatedreq, delegateemp, deptemp); email.emailTo = delegateemp.Email; email.emailSubject = srf.subject; email.emailBody = srf.body; await mailservice.SendEmailAsync(email); }); } return(true); }