public async Task <ActionResult> SendEmail([FromForm] SendEmailModel model) { if (!ModelState.IsValid) { return(View(model)); } model.Succes = await _mailHandler.SendEmailAsync(model); model.Content = string.Empty; return(View(model)); }
public async Task SendNotificationAsync() { var notifications = await _notificationRepository.SearchAsync(new NotificationFilter()); var users = (await _userRepository.GetByIdAsync(notifications.Select(n => n.UserId))).ToDictionary(i => i.Id, i => i); foreach (var notification in notifications) { var filter = JsonConvert.DeserializeObject <PetFilter>(notification.PetFilterSerialized); filter.CreatedSince = DateTime.Now.Date; var user = users[notification.UserId]; var pets = await _petRepository.SearchAsync(filter); if (pets.Count() == 0) { continue; } var attachment = new List <Attachment>(); if (await EmailExists(user.Id, notification.Id, DateTime.Now.Date)) { continue; } string mailTemplate = GetResource("notification-email.html") .Replace("{{user.Name}}", user.Name); string petRowTemplate = GetResource("notification-pet-row.html"); StringBuilder sbPets = new StringBuilder(); int fileCount = 0; foreach (var pet in pets) { string html = petRowTemplate .Replace("{{pet.Name}}", pet.Name) .Replace("{{pet.Description}}", pet.Description) .Replace("{{pet.SourceLink}}", pet.SourceLink); using (var client = new WebClient()) { var content = client.DownloadData(Path.Combine(Constants.StorageUrl, pet.MetaFileLinks.First().Path)); using (var ms = new MemoryStream(content)) { string imageName = $"image{fileCount++}.jpg"; var fileBytes = ms.ToArray(); attachment.Add(new Attachment(new MemoryStream(fileBytes), imageName)); html = html.Replace("{{pet-image}}", $"cid:{imageName}"); } } sbPets.AppendLine(html); } var bodyHtml = mailTemplate.Replace("{{pets-html}}", sbPets.ToString()); var mail = new MailRequest() { To = user.Email, Subject = "בעלי חיים חדשים מחכים לאימוץ!", Body = bodyHtml, Attachments = attachment }; await _mailHandler.SendEmailAsync(mail); var emailHistory = new EmailHistory() { UpdatedTimestamp = DateTime.Now, UserId = user.Id, NotificationId = notification.Id, CreationTimestamp = DateTime.Now, SentDate = DateTime.Now.Date }; await _emailHistoryRepository.AddAsync(emailHistory); await _unitOfWork.SaveChangesAsync(); } }