public async Task <ActionResult <UserRegisterResponseVM> > Register([FromBody] UserRegisterVM vm)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Invalid Data"));
            }
            else if (vm.Password != vm.PasswordConfirmation)
            {
                return(BadRequest("Password and password confirmation do not match"));
            }
            else
            {
                var entity = await _context.Cities.SingleOrDefaultAsync(b => b.Name == vm.City);

                if (entity == null)
                {
                    return(BadRequest("Could not find city"));
                }
            }

            //var user = new User(vm);
            var user = new User
            {
                UserName        = vm.Email,
                Email           = vm.Email,
                FirstName       = vm.FirstName,
                LastName        = vm.LastName,
                NormalizedEmail = _normalizer.NormalizeEmail(vm.Email),
                Tos             = vm.Tos,
                PhoneNumber     = vm.Phone,
                CityName        = vm.City
            };
            var result = await _userManager.CreateAsync(user, vm.Password);

            //result = await _userManager.AddPasswordAsync(user, vm.Password);
            if (result.Succeeded)
            {
                await _userManager.AddToRoleAsync(user, "user");

                //normalize
                await _userManager.UpdateNormalizedEmailAsync(user);

                //generate email confirmation token
                var confirmation = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                //email token to user
                var apiKey           = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
                var client           = new SendGridClient(apiKey);
                var from             = new EmailAddress("*****@*****.**", "Example User");
                var subject          = "You are now registered!";
                var to               = new EmailAddress(vm.Email, vm.FirstName);
                var plainTextContent = "Confirmation: " + confirmation;
                var htmlContent      = "Confirmation: " + confirmation;
                var msg              = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
                var response         = await client.SendEmailAsync(msg);

                return(Ok(new UserRegisterResponseVM("200 ok, awesome!")));
            }
            else
            {
                return(BadRequest("Register failed :("));
            }
        }
Esempio n. 2
0
        static async Task Execute()
        {
            // Retrieve the API key from the environment variables. See the project README for more info about setting this up.
            var apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY");

            var client = new SendGridClient(apiKey);

            // Send a Single Email using the Mail Helper
            var from             = new EmailAddress("*****@*****.**", "Example User");
            var subject          = "Hello World from the SendGrid CSharp Library Helper!";
            var to               = new EmailAddress("*****@*****.**", "Example User");
            var plainTextContent = "Hello, Email from the helper [SendSingleEmailAsync]!";
            var htmlContent      = "<strong>Hello, Email from the helper! [SendSingleEmailAsync]</strong>";
            var msg              = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);

            var response = await client.SendEmailAsync(msg);

            Console.WriteLine(msg.Serialize());
            Console.WriteLine(response.StatusCode);
            Console.WriteLine(response.Headers);
            Console.WriteLine("\n\nPress <Enter> to continue.");
            Console.ReadLine();

            // Send a Single Email using the Mail Helper with convenience methods and initialized SendGridMessage object
            msg = new SendGridMessage()
            {
                From             = new EmailAddress("*****@*****.**", "Example User"),
                Subject          = "Hello World from the SendGrid CSharp Library Helper!",
                PlainTextContent = "Hello, Email from the helper [SendSingleEmailAsync]!",
                HtmlContent      = "<strong>Hello, Email from the helper! [SendSingleEmailAsync]</strong>"
            };
            msg.AddTo(new EmailAddress("*****@*****.**", "Example User"));

            response = await client.SendEmailAsync(msg);

            Console.WriteLine(msg.Serialize());
            Console.WriteLine(response.StatusCode);
            Console.WriteLine(response.Headers);
            Console.WriteLine("\n\nPress <Enter> to continue.");
            Console.ReadLine();

            // Send a Single Email using the Mail Helper, entirely with convenience methods
            msg = new SendGridMessage();
            msg.SetFrom(new EmailAddress("*****@*****.**", "Example User"));
            msg.SetSubject("Hello World from the SendGrid CSharp Library Helper!");
            msg.AddContent(MimeType.Text, "Hello, Email from the helper [SendSingleEmailAsync]!");
            msg.AddContent(MimeType.Html, "<strong>Hello, Email from the helper! [SendSingleEmailAsync]</strong>");
            msg.AddTo(new EmailAddress("*****@*****.**", "Example User"));

            response = await client.SendEmailAsync(msg);

            Console.WriteLine(msg.Serialize());
            Console.WriteLine(response.StatusCode);
            Console.WriteLine(response.Headers);
            Console.WriteLine("\n\nPress <Enter> to continue.");
            Console.ReadLine();

            // Send a Single Email Without the Mail Helper
            string data = @"{
              'personalizations': [
                {
                  'to': [
                    {
                      'email': '*****@*****.**'
                    }
                  ],
                  'subject': 'Hello World from the SendGrid C# Library!'
                }
              ],
              'from': {
                'email': '*****@*****.**'
              },
              'content': [
                {
                  'type': 'text/plain',
                  'value': 'Hello, Email!'
                }
              ]
            }";
            var    json = JsonConvert.DeserializeObject <object>(data);

            response = await client.RequestAsync(SendGridClient.Method.POST,
                                                 json.ToString(),
                                                 urlPath : "mail/send");

            Console.WriteLine(response.StatusCode);
            Console.WriteLine(response.Headers);
            Console.WriteLine("\n\nPress <Enter> to continue.");
            Console.ReadLine();

            // GET Collection
            string queryParams = @"{
                'limit': 100
            }";

            response = await client.RequestAsync(method : SendGridClient.Method.GET,
                                                 urlPath : "asm/groups",
                                                 queryParams : queryParams);

            Console.WriteLine(response.StatusCode);
            Console.WriteLine(response.Body.ReadAsStringAsync().Result);
            Console.WriteLine(response.Headers);
            Console.WriteLine("\n\nPress <Enter> to continue to POST.");
            Console.ReadLine();

            // POST
            string requestBody = @"{
              'description': 'Suggestions for products our users might like.', 
              'is_default': false, 
              'name': 'Magic Products'
            }";

            json     = JsonConvert.DeserializeObject <object>(requestBody);
            response = await client.RequestAsync(method : SendGridClient.Method.POST,
                                                 urlPath : "asm/groups",
                                                 requestBody : json.ToString());

            var ds_response = JsonConvert.DeserializeObject <Dictionary <string, dynamic> >(response.Body.ReadAsStringAsync().Result);

            Console.WriteLine(response.StatusCode);
            Console.WriteLine(response.Body.ReadAsStringAsync().Result);
            Console.WriteLine(response.Headers);
            Console.WriteLine("\n\nPress <Enter> to continue to GET single.");
            Console.ReadLine();

            if (ds_response != null && ds_response.ContainsKey("id"))
            {
                string group_id = ds_response["id"].ToString();


                // GET Single
                response = await client.RequestAsync(method : SendGridClient.Method.GET,
                                                     urlPath : string.Format("asm/groups/{0}", group_id));

                Console.WriteLine(response.StatusCode);
                Console.WriteLine(response.Body.ReadAsStringAsync().Result);
                Console.WriteLine(response.Headers);
                Console.WriteLine("\n\nPress <Enter> to continue to PATCH.");
                Console.ReadLine();

                // PATCH
                requestBody = @"{
                    'name': 'Cool Magic Products'
                }";
                json        = JsonConvert.DeserializeObject <object>(requestBody);

                response = await client.RequestAsync(method : SendGridClient.Method.PATCH,
                                                     urlPath : string.Format("asm/groups/{0}", group_id),
                                                     requestBody : json.ToString());

                Console.WriteLine(response.StatusCode);
                Console.WriteLine(response.Body.ReadAsStringAsync().Result);
                Console.WriteLine(response.Headers.ToString());

                Console.WriteLine("\n\nPress <Enter> to continue to PUT.");
                Console.ReadLine();

                // DELETE
                response = await client.RequestAsync(method : SendGridClient.Method.DELETE,
                                                     urlPath : string.Format("asm/groups/{0}", group_id));

                Console.WriteLine(response.StatusCode);
                Console.WriteLine(response.Headers.ToString());
                Console.WriteLine("\n\nPress <Enter> to DELETE and exit.");
                Console.ReadLine();
            }
        }
        public async Task SendEmailCart(List <ProductoCarrito> productos, User user, CommissionHotel hotel)
        {
            var     correo = user.Correo;
            var     htmlContentProductList = "";
            decimal totalPrice             = 0;

            for (int i = 0; i < productos.Count; i++)
            {
                totalPrice += productos.ElementAt(i).PrecioBruto;

                var htmlContentMain = string.Format(@"
            <tr class='item'>
                <td style='padding: 5px; vertical-align: top;'>
                    " + $@"{productos.ElementAt(i).NombreProducto}" + $@" (x{ productos.ElementAt(i).Cant})" + @"
                </td>
                
                <td style='padding: 5px; vertical-align: top;'>
                    $" + $@"{productos.ElementAt(i).PrecioBruto}" + @"
                </td>
            </tr>");
                htmlContentProductList += htmlContentMain;
            }


            var client           = new SendGridClient("sendgrid_key");
            var from             = new EmailAddress("*****@*****.**", "Stay n'Chill");
            var subject          = "Factura de Compra";
            var to               = new EmailAddress(correo);
            var plainTextContent = "";



            var htmlContent = string.Format(@"<div style='margin-top:5rem; max-width: 800px; margin: auto; padding: 30px; border: 1px solid #eee; box-shadow: 0 0 10px rgba(0, 0, 0, .15); font-size: 16px; line-height: 24px; font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; color: #555; border-radius: 7px;'>
        <table cellpadding='0' cellspacing='0' style='width: 100%; line-height: inherit; text-align: left;'>
            <tr style='font-size: 45px;
            line-height: 45px;
            color: #333;padding-bottom: 40px;'>
                <td colspan='2' style='padding: 5px; vertical-align: top;'>
                    <table style='width: 100%; line-height: inherit; text-align: left;'>
                        <tr>
                            <td  style='font-size: 45px;
                            line-height: 45px;
                            color: #333;padding: 5px; vertical-align: top;'>
                                <img src='https://res.cloudinary.com/qubitscenfo/image/upload/v1565417512/ckxg43ppvqlizl1mzzie.png' style='width:100%; max-width:300px;'>
                            </td>
                            
                            
                        </tr>
                    </table>
                </td>
            </tr>
            
            <tr class='information'>
                <td colspan='2' style='padding: 5px; vertical-align: top;'>
                    <table>
                        
                    </table>
                </td>
            </tr>
            
            <tr class='heading'>
                <td style='padding: 5px; vertical-align: top;'>
                    Método de Pago
                </td>
                
                <td style='padding: 5px; vertical-align: top;'>
                    PayPal
                </td>
            </tr>
            
            
            
            <tr class='heading'>
                <td style='padding: 5px; vertical-align: top;'>
                    Item
                </td>
                
                <td style='padding: 5px; vertical-align: top;'>
                    Precio
                </td>
            </tr>
            
            " + $@"{htmlContentProductList}" + @"
            
            <tr class='total'>
                <td>
                    
                </td>
                <td>
                   Total: USD " + $@"{totalPrice}" + @"
                </td>
            </tr>
        </table>
    </div>");

            var msg      = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
            var response = await client.SendEmailAsync(msg);
        }
Esempio n. 4
0
        //Payment
        public void SendEmailReceiptForBuyer(int routeId)
        {
            try
            {
                var    apiKey             = SETTING.Value.SendGridKey;
                var    client             = new SendGridClient(apiKey);
                string emailTemplateHtml  = _hostingEnvironment.ContentRootPath + "\\EmailTemplate\\EmailTemplate.html";
                string ticketTemplatehtml = _hostingEnvironment.ContentRootPath + "\\EmailTemplate\\TicketsTemplate.html";
                string body       = string.Empty;
                string ticketList = string.Empty;
                var    route      = _routeRepository.Get(r => r.Id == routeId);
                var    customer   = _customerRepository.Get(c => c.Id == route.CustomerId);
                //using streamreader for reading my htmltemplate
                using (StreamReader reader = new StreamReader(emailTemplateHtml))
                {
                    body = reader.ReadToEnd();
                }
                var customerEmail = _customerRepository.Get(c => c.Id == route.CustomerId).Email;
                var customerName  = customer.FullName;
                var customerPhone = customer.PhoneNumber;
                var routeCode     = route.Code;
                var totalAmount   = route.TotalAmount;
                var date          = DateTime.UtcNow;
                var routeTickets  = _routeTicketRepository.GetAllQueryable().Where(r => r.RouteId == routeId);
                List <TicketRowViewModel> tickets = new List <TicketRowViewModel>();
                foreach (var routeTicket in routeTickets)
                {
                    var ticket             = _ticketRepository.Get(t => t.Id == routeTicket.TicketId);
                    var ticketRowViewModel = _mapper.Map <Ticket, TicketRowViewModel>(ticket);
                    tickets.Add(ticketRowViewModel);
                }
                //replacing the required things
                body = body.Replace("{routeCode}", routeCode);
                body = body.Replace("{customerName}", customerName);
                body = body.Replace("{customerEmail}", customerEmail);
                body = body.Replace("{customerPhone}", customerPhone);
                body = body.Replace("{Date}", date.ToString());
                body = body.Replace("{subTotal}", totalAmount.ToString());
                body = body.Replace("{Total}", totalAmount.ToString());

                body = body.Replace("{Term}", SETTING.Value.Term);
                body = body.Replace("{Title}", SETTING.Value.Title);
                body = body.Replace("{fromName}", SETTING.Value.FromName);
                body = body.Replace("{fromEmail}", SETTING.Value.FromEmail);
                body = body.Replace("{Street}", SETTING.Value.Street);
                body = body.Replace("{City}", SETTING.Value.City);
                body = body.Replace("{addressNumber}", SETTING.Value.AddressNumber);
                body = body.Replace("{phoneNumber}", SETTING.Value.PhoneNumber);
                body = body.Replace("{bussinessNumber}", SETTING.Value.BussinessNumber);
                foreach (var ticket in tickets)
                {
                    using (StreamReader reader = new StreamReader(ticketTemplatehtml))
                    {
                        var ticketRow        = reader.ReadToEnd();
                        var departureStation = _stationRepository.Get(s => s.Id == ticket.DepartureStationId).Name;
                        var arrivalStation   = _stationRepository.Get(s => s.Id == ticket.ArrivalStationId).Name;
                        ticketRow = ticketRow.Replace("{ticketCode}", ticket.TicketCode);
                        ticketRow = ticketRow.Replace("{Description}", ticket.Description);
                        ticketRow = ticketRow.Replace("{departureCity}", ticket.DepartureCity);
                        ticketRow = ticketRow.Replace("{departureStation}", departureStation);
                        ticketRow = ticketRow.Replace("{departureTime}", ticket.DepartureDateTime.ToString());
                        ticketRow = ticketRow.Replace("{arrivalCity}", ticket.ArrivalCity);
                        ticketRow = ticketRow.Replace("{arrivalStation}", arrivalStation);
                        ticketRow = ticketRow.Replace("{arrivalTime}", ticket.ArrivalDateTime.ToString());
                        ticketRow = ticketRow.Replace("{Amount}", ticket.SellingPrice.ToString());

                        ticketList += ticketRow;
                    }
                }
                body = body.Replace("{ticketList}", ticketList);

                var from             = new EmailAddress(SETTING.Value.FromEmail, SETTING.Value.FromName);
                var subject          = routeCode + " - Receipt - Payment";
                var to               = new EmailAddress(customerEmail, customerName);
                var plainTextContent = "";
                var htmlContent      = body;
                var msg              = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
                client.SendEmailAsync(msg);
            }
            catch (Exception)
            {
            }
        }
Esempio n. 5
0
        public async Task SendEmailAsync(IEmailAddress from, IEnumerable <IEmailAddress> recipients, IEnumerable <IEmailAddress> ccRecipients, IEnumerable <IEmailAddress> bccRecipients, string subject, string text, string html, IEnumerable <IEmailAttachment> attachments, IEmailAddress replyTo = null)
        {
            var allRecipients = new List <IEmailAddress>(recipients);

            allRecipients.AddRange(ccRecipients);
            allRecipients.AddRange(bccRecipients);

            if (allRecipients.GroupBy(r => r.Email).Count() < allRecipients.Count)
            {
                throw new ArgumentException("Each email address should be unique between to, cc, and bcc recipients. We found duplicates.");
            }

            var client = new SendGridClient(this.apiKey);

            SendGridMessage message;

            if (recipients.Count() == 1)
            {
                message = MailHelper.CreateSingleEmail(from.ToSendGridEmail(), recipients.First().ToSendGridEmail(), subject, text, html);
            }
            else
            {
                message = MailHelper.CreateSingleEmailToMultipleRecipients(
                    from.ToSendGridEmail(),
                    recipients.Select(email => email.ToSendGridEmail()).ToList(),
                    subject,
                    text,
                    html);
            }

            foreach (var ccRecipient in ccRecipients)
            {
                message.AddCc(ccRecipient.Email, ccRecipient.DisplayName);
            }

            foreach (var bccRecipient in bccRecipients)
            {
                message.AddBcc(bccRecipient.Email, bccRecipient.DisplayName);
            }

            if (attachments.Any())
            {
                message.AddAttachments(attachments.Select(a => new Attachment
                {
                    Filename = a.FileName,
                    Type     = a.ContentType,
                    Content  = Convert.ToBase64String(a.Data)
                }).ToList());
            }

            if (replyTo != null)
            {
                message.ReplyTo = replyTo.ToSendGridEmail();
            }

            var response = await client.SendEmailAsync(message);

            if (response.StatusCode != System.Net.HttpStatusCode.Accepted)
            {
                throw new Exception($"Cannot Send Email: {response.StatusCode}");
            }
        }
Esempio n. 6
0
 public async Task SendEmailAsync(string email, string subject, string htmlMessage)
 {
     var client   = new SendGridClient(_apiKey);
     var msg      = MailHelper.CreateSingleEmail(new EmailAddress(_fromEmail, "BOS Team"), new EmailAddress(email), subject, "", htmlMessage);
     var response = await client.SendEmailAsync(msg);
 }
Esempio n. 7
0
        //Refund All Ticket
        public void SendEmailRefundForBuyerAllTicket(int routeId, decimal remainRefund)
        {
            try
            {
                var    apiKey             = SETTING.Value.SendGridKey;
                var    client             = new SendGridClient(apiKey);
                string emailTemplateHtml  = _hostingEnvironment.ContentRootPath + "\\EmailTemplate\\EmailTemplateRefund.html";
                string ticketTemplatehtml = _hostingEnvironment.ContentRootPath + "\\EmailTemplate\\TicketsTemplate.html";
                string body       = string.Empty;
                string ticketList = string.Empty;
                var    route      = _routeRepository.Get(r => r.Id == routeId);
                var    customer   = _customerRepository.Get(c => c.Id == route.CustomerId);
                //using streamreader for reading my htmltemplate
                using (StreamReader reader = new StreamReader(emailTemplateHtml))
                {
                    body = reader.ReadToEnd();
                }
                var customerEmail = customer.Email;
                var customerName  = customer.FullName;
                var totalAmount   = route.TotalAmount;
                var routeCode     = route.Code;
                var routeTickets  = _routeTicketRepository.GetAllQueryable()
                                    .Where(r => r.RouteId == routeId && r.IsReplaced != true)
                                    .OrderBy(r => r.Order);
                var firstTicket = routeTickets.FirstOrDefault();
                var lastTicket  = routeTickets.LastOrDefault();

                //replacing the required things
                body = body.Replace("{customerName}", customerName);
                body = body.Replace("{subTotal}", remainRefund.ToString());
                body = body.Replace("{Total}", remainRefund.ToString());

                body = body.Replace("{refundTitle}", SETTING.Value.RefundTitle);
                body = body.Replace("{fromName}", SETTING.Value.FromName);

                using (StreamReader reader = new StreamReader(ticketTemplatehtml))
                {
                    var ticketRow         = reader.ReadToEnd();
                    var departureStation  = firstTicket.DepartureStation.Name;
                    var arrivalStation    = lastTicket.ArrivalStation.Name;
                    var departureCity     = firstTicket.DepartureStation.City.Name;
                    var arrivalCity       = lastTicket.ArrivalStation.City.Name;
                    var departureDateTime = firstTicket.Ticket.DepartureDateTime;
                    var arrivalDateTime   = lastTicket.Ticket.ArrivalDateTime;

                    ticketRow = ticketRow.Replace("{ticketCode}", routeCode);
                    ticketRow = ticketRow.Replace("{Description}", "");
                    ticketRow = ticketRow.Replace("{departureCity}", departureCity);
                    ticketRow = ticketRow.Replace("{departureStation}", departureStation);
                    ticketRow = ticketRow.Replace("{departureTime}", String.Format("{0:dddd, MMMM dd, yyyy HH:mm}", departureDateTime));
                    ticketRow = ticketRow.Replace("{arrivalCity}", arrivalCity);
                    ticketRow = ticketRow.Replace("{arrivalStation}", arrivalStation);
                    ticketRow = ticketRow.Replace("{arrivalTime}", String.Format("{0:dddd, MMMM dd, yyyy HH:mm}", arrivalDateTime));
                    ticketRow = ticketRow.Replace("{Amount}", remainRefund.ToString());

                    ticketList += ticketRow;
                }

                body = body.Replace("{ticketList}", ticketList);

                var from             = new EmailAddress(SETTING.Value.FromEmail, SETTING.Value.FromName);
                var subject          = routeCode + " - Receipt - Refund All";
                var to               = new EmailAddress(customerEmail, customerName);
                var plainTextContent = "";
                var htmlContent      = body;
                var msg              = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
                client.SendEmailAsync(msg);
            }
            catch (Exception)
            {
            }
        }
        public async Task <bool> SendEmailAsync(string receiverEmail, string providerUserName, string hostname = "")
        {
            var bResponse = false;

            try
            {
                var      pra      = accessor.HttpContext.Session.GetString("practice");
                var      username = accessor.HttpContext.Session.GetString("name");
                Practice practice = FewaDbContext.practices.Where(a => a.url == pra).FirstOrDefault();
                if (practice == null)
                {
                    return(false);
                }
                var provider = _providerRepository.getProviderByUserName(practice.name, providerUserName);
                if (provider == null)
                {
                    return(false);
                }
                if (!string.IsNullOrEmpty(hostname))
                {
                    practice.serverName = hostname;
                }
                //var TodaysDate =DateTime.Now.ToString("MM-dd-yyyy HH:mm:ss");
                var client      = new SendGridClient(practice.emailApiKey);
                var from        = new EmailAddress(practice.email);
                var to          = new EmailAddress(receiverEmail);
                var htmlContent = practice.emailHtmlBody;
                htmlContent = htmlContent.Replace("{imageUrl}", practice.serverName + practice.logoPath);
                htmlContent = htmlContent.Replace("{join}", practice.serverName + "/" + provider.practice + "/" + provider.url + "/#/patient/intro");
                htmlContent = htmlContent.Replace("providerNameTitle", provider.nameTitle);
                if (string.IsNullOrEmpty(provider.name))
                {
                    htmlContent = htmlContent.Replace("providerName", provider.userName);
                }
                else
                {
                    htmlContent = htmlContent.Replace("providerName", provider.name);
                }
                htmlContent = htmlContent.Replace("practiceName", practice.name);
                htmlContent = htmlContent.Replace("{serverName}", practice.serverName);
                htmlContent = htmlContent.Replace("PatientEmail", receiverEmail);
                if (practice.emailAdditionalContent == "EmailAdditionalContent")
                {
                    htmlContent = htmlContent.Replace("EmailAdditionalContent", "");
                }
                else
                {
                    htmlContent = htmlContent.Replace("EmailAdditionalContent", practice.emailAdditionalContent);
                }
                var msg = MailHelper.CreateSingleEmail(from, to, practice.emailSubject, practice.emailPlainBody, htmlContent);
                var res = await client.SendEmailAsync(msg);

                if (res.StatusCode == System.Net.HttpStatusCode.OK || res.StatusCode == System.Net.HttpStatusCode.Accepted)
                {
                    bResponse = true;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"file: MessengerController.cs method: SendEmailAsync() error: {ex.Message} ");
            }
            return(bResponse);
        }
Esempio n. 9
0
        public async Task SendEmailAsync(string email, string subject, string message)
        {
            if (this.appConfig.EmailDeliveryMethod == "SendGrid")
            {
                var apiKey           = this.appConfig.SendGridApiKey;
                var client           = new SendGridClient(apiKey);
                var from             = new EmailAddress(this.appConfig.NoReplyEmail);
                var to               = new EmailAddress(email);
                var plainTextContent = Regex.Replace(message, "<[^>]*>", "");
                var msg              = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, message);
                await client.SendEmailAsync(msg);
            }
            else if (this.appConfig.EmailDeliveryMethod == "LocalFolder")
            {
                string path = Path.Combine(this.hostingEnvironment.ContentRootPath, "Temp", "Emails");
                Directory.CreateDirectory(path);

                var client = new SmtpClient("smtp.example.com")
                {
                    DeliveryMethod          = SmtpDeliveryMethod.SpecifiedPickupDirectory,
                    PickupDirectoryLocation = path
                };
                var mailMessage = new MailMessage
                {
                    From       = new MailAddress(this.appConfig.NoReplyEmail),
                    To         = { email },
                    Body       = message,
                    Subject    = subject,
                    IsBodyHtml = true
                };
                await client.SendMailAsync(mailMessage);
            }
            else if (this.appConfig.EmailDeliveryMethod == "Mailjet")
            {
                var mailjetClient = new MailjetClient(
                    this.appConfig.MailJetApiKey,
                    this.appConfig.MailJetApiSecret)
                {
                    Version = ApiVersion.V3
                };

                var mailJetRequest = new MailjetRequest
                {
                    Resource = Send.Resource
                }
                .Property(Send.FromEmail, this.appConfig.NoReplyEmail)
                .Property(Send.Subject, subject)
                .Property(Send.HtmlPart, message)
                .Property(Send.To, email);

                try
                {
                    await mailjetClient.PostAsync(mailJetRequest);
                }
                catch (Exception e)
                {
                    //Todo log error
                }
            }
            else
            {
                throw new ApplicationException("Email delivery method is invalid.");
            }
        }
        public async Task <bool> SendRegistrationOTP(string practiceName, string receiverEmail, string otp, string hostname = "")
        {
            var bResponse = false;

            try
            {
                Practice practice = FewaDbContext.practices.Where(a => a.email == receiverEmail || a.name == practiceName || a.url == practiceName.ToLower().Trim()).FirstOrDefault();
                if (practice != null)
                {
                    return(false);
                }
                var emailPlainBody = "";
                var htmlContent    = "   <table align='center' cellpadding='0' cellspacing='0' border='0' width='100%'bgcolor='#f0f0f0'>  " +
                                     "           <tr>  " +
                                     "           <td style='padding: 30px 30px 20px 30px;'>  " +
                                     "               <table cellpadding='0' cellspacing='0' border='0' width='100%' bgcolor='#ffffff' style='margin: auto;'>  " +
                                     "               <tr>  " +
                                     "                   <td colspan='2' align='center' style='padding: 50px 50px 0px 50px;'>  " +
                                     "                       <h1 style='padding-right: 0em; margin: 0; line-height: 40px; font-weight:300; font-family: \"Nunito Sans\", Arial, Verdana, Helvetica, sans-serif; color: #666; text-align: left; padding-bottom: 1em;'>  " +
                                     "                         Email verification for new practice  " +
                                     "                       </h1>  " +
                                     "                   </td>  " +
                                     "               </tr>  " +
                                     "               <tr>  " +
                                     "                   <td style='text-align: left; padding: 0px 50px;' valign='top'>  " +
                                     "                       <p style='font-size: 18px; margin: 0; line-height: 24px; font-family: \"Nunito Sans\", Arial, Verdana, Helvetica, sans-serif; color: #666; text-align: left; padding-bottom: 3%;'>  " +
                                     "                           Hi " + receiverEmail + ",  " +
                                     "                       </p>  " +
                                     "                       <p style='font-size: 18px; margin: 0; line-height: 24px; font-family: \"Nunito Sans\", Arial, Verdana, Helvetica, sans-serif; color: #666; text-align: left; padding-bottom: 3%;'>  " +
                                     "                           Seems like you have to verify your email for Fewa Telehealth. If this is true, use below one time password to validate your email address.  " +
                                     "                       </p>  " +
                                     "   					<h1 style='padding-right: 0em; margin: 0; line-height: 0px; font-weight:300; font-family: \"Nunito Sans\", Arial, Verdana, Helvetica, sans-serif; color: #666; text-align: left; padding-bottom: 1em; font-size: 25px;'>  "+
                                     "                           " + otp + "  " +
                                     "                       </h1>  " +
                                     "   					<p style='font-size: 18px; margin: 0; line-height: 24px; font-family: \"Nunito Sans\", Arial, Verdana, Helvetica, sans-serif; color: #666; text-align: left; padding-bottom: 3%;'>  "+
                                     "   						<strong>Note:</strong>&nbsp; One time password is case sensitive.<br>  "+
                                     "                       </p>  " +
                                     "                   </td>  " +
                                     "               </tr>  " +
                                     "               <tr>  " +
                                     "                   <td style='text-align: left; padding: 30px 50px 50px 50px' valign='top'>  " +
                                     "                       <p style='font-size: 18px; margin: 0; line-height: 24px; font-family: \"Nunito Sans\", Arial, Verdana, Helvetica, sans-serif; color: #505050; text-align: left;'>  " +
                                     "                           Thanks,<br/>Fewa Team  " +
                                     "                       </p>  " +
                                     "                   </td>  " +
                                     "               </tr>  " +
                                     "               <tr>  " +
                                     "                   <td colspan='2' align='center' style='padding: 20px 40px 40px 40px;' bgcolor='#f0f0f0'>  " +
                                     "                       <p style='font-size: 12px; margin: 0; line-height: 24px; font-family: \"Nunito Sans\", Arial, Verdana, Helvetica, sans-serif; color: #777;'>  " +
                                     "                           Powered by &copy; 2020  Fewa Telehealth" +
                                     "                       </p>  " +
                                     "                   </td>  " +
                                     "               </tr>  " +
                                     "               </table>  " +
                                     "           </td>  " +
                                     "       </tr>  " +
                                     "  </table>  ";
                var      emailSubject = "Email verification for new practice";
                Practice pra          = FewaDbContext.practices.Where(a => a.url == "practice").FirstOrDefault();
                if (pra == null)
                {
                    return(false);
                }
                var client = new SendGridClient(pra.emailApiKey);
                var from   = new EmailAddress(pra.email);
                var to     = new EmailAddress(receiverEmail);

                var msg = MailHelper.CreateSingleEmail(from, to, emailSubject, emailPlainBody, htmlContent);
                var res = await client.SendEmailAsync(msg);

                if (res.StatusCode == System.Net.HttpStatusCode.OK || res.StatusCode == System.Net.HttpStatusCode.Accepted)
                {
                    bResponse = true;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"file: SecurityController.cs method: SendOtpAsync() error: {ex.Message} ");
            }
            return(bResponse);
        }
        public async Task <bool> SendPatientReportEmailAsync(Patient patient, string hostname = "")
        {
            var bResponse = false;

            try
            {
                Provider provider = FewaDbContext.providers.Where(a => a.url == patient.url).FirstOrDefault();
                if (provider == null)
                {
                    return(false);
                }
                Practice practice = FewaDbContext.practices.Where(a => a.url == provider.practice).FirstOrDefault();
                if (practice == null)
                {
                    return(false);
                }

                if (!string.IsNullOrEmpty(hostname))
                {
                    practice.serverName = hostname;
                }
                var adviceList = "";
                var client     = new SendGridClient(practice.emailApiKey);
                var from       = new EmailAddress(practice.email);
                var to         = new EmailAddress(patient.email);
                List <ProviderAdvice> getAllAdvice = patient.advice.ToList();
                for (var i = 0; i < getAllAdvice.Count; i++)
                {
                    var value = getAllAdvice[i].isChecked == true ? "Yes" : "No";
                    var adv   = getAllAdvice.ElementAt(i).advice;
                    adviceList += "<tr><td align='left' valign='top' style = 'font-family:\"Open Sans\", Arial, sans-serif; font-size:14px; line-height:22px; color:#666;padding-bottom:12px;'>" +
                                  "<b style='color:#000;'>" + adv + ":</b>&nbsp;" + value + "</td></tr>";
                }
                //var labOrdersSent = patient.labOrdersSent == true ? "Yes" : "No";
                //var newPrescriptionsSentToYourPharmacy = patient.newPrescriptionsSentToYourPharmacy == true ? "Yes" : "No";
                //var newPrescriptionsMailedToYou = patient.newPrescriptionsMailedToYou == true ? "Yes" : "No";
                var htmlContent = "   <!DOCTYPE html>  " +
                                  "   <html lang='en'>  " +
                                  "     " +
                                  "   <head>  " +
                                  "       <meta charset='UTF-8'>  " +
                                  "       <meta name='viewport' content='width=device-width, initial-scale=1.0'>  " +
                                  "       <title>Fema mailer</title>  " +
                                  "       <link href=“https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700,800” rel=“stylesheet”>  " +
                                  "     " +
                                  "       <style type='text/css'>  " +
                                  "           body {  " +
                                  "               margin: 0 !important;  " +
                                  "               padding: 0 !important;  " +
                                  "               -webkit-text-size-adjust: 100% !important;  " +
                                  "               -ms-text-size-adjust: 100% !important;  " +
                                  "               -webkit-font-smoothing: antialiased !important;  " +
                                  "           }  " +
                                  "     " +
                                  "           img {  " +
                                  "               border: 0 !important;  " +
                                  "               outline: none !important;  " +
                                  "           }  " +
                                  "     " +
                                  "           p {  " +
                                  "               Margin: 0px !important;  " +
                                  "               Padding: 0px !important;  " +
                                  "           }  " +
                                  "     " +
                                  "           table {  " +
                                  "               border-collapse: collapse;  " +
                                  "               mso-table-lspace: 0px;  " +
                                  "               mso-table-rspace: 0px;  " +
                                  "           }  " +
                                  "     " +
                                  "           td,  " +
                                  "           a,  " +
                                  "           span {  " +
                                  "               border-collapse: collapse;  " +
                                  "               mso-line-height-rule: exactly;  " +
                                  "           }  " +
                                  "     " +
                                  "           .ExternalClass ' {  " +
                                  "               line-height: 100%;  " +
                                  "           }  " +
                                  "     " +
                                  "           .em_defaultlink a {  " +
                                  "               color: inherit !important;  " +
                                  "               text-decoration: none !important;  " +
                                  "           }  " +
                                  "     " +
                                  "           span.MsoHyperlink {  " +
                                  "               mso-style-priority: 99;  " +
                                  "               color: inherit;  " +
                                  "           }  " +
                                  "     " +
                                  "           span.MsoHyperlinkFollowed {  " +
                                  "               mso-style-priority: 99;  " +
                                  "               color: inherit;  " +
                                  "           }  " +
                                  "     " +
                                  "           @media only screen and (min-width:481px) and (max-width:699px) {  " +
                                  "               .em_main_table {  " +
                                  "                   width: 100% !important;  " +
                                  "               }  " +
                                  "     " +
                                  "               .em_wrapper {  " +
                                  "                   width: 100% !important;  " +
                                  "               }  " +
                                  "     " +
                                  "               .em_hide {  " +
                                  "                   display: none !important;  " +
                                  "               }  " +
                                  "     " +
                                  "               .em_img {  " +
                                  "                   width: 100% !important;  " +
                                  "                   height: auto !important;  " +
                                  "               }  " +
                                  "     " +
                                  "               .em_h20 {  " +
                                  "                   height: 20px !important;  " +
                                  "               }  " +
                                  "     " +
                                  "               .em_padd {  " +
                                  "                   padding: 20px 10px !important;  " +
                                  "               }  " +
                                  "           }  " +
                                  "     " +
                                  "           @media screen and (max-width: 480px) {  " +
                                  "               .em_main_table {  " +
                                  "                   width: 100% !important;  " +
                                  "               }  " +
                                  "     " +
                                  "               .em_wrapper {  " +
                                  "                   width: 100% !important;  " +
                                  "               }  " +
                                  "     " +
                                  "               .em_hide {  " +
                                  "                   display: none !important;  " +
                                  "               }  " +
                                  "     " +
                                  "               .em_img {  " +
                                  "                   width: 100% !important;  " +
                                  "                   height: auto !important;  " +
                                  "               }  " +
                                  "     " +
                                  "               .em_h20 {  " +
                                  "                   height: 20px !important;  " +
                                  "               }  " +
                                  "     " +
                                  "               .em_padd {  " +
                                  "                   padding: 20px 10px !important;  " +
                                  "               }  " +
                                  "     " +
                                  "               .em_text1 {  " +
                                  "                   font-size: 16px !important;  " +
                                  "                   line-height: 24px !important;  " +
                                  "               }  " +
                                  "     " +
                                  "               u+.em_body .em_full_wrap {  " +
                                  "                   width: 100% !important;  " +
                                  "                   width: 100vw !important;  " +
                                  "               }  " +
                                  "           }  " +
                                  "       </style>  " +
                                  "     " +
                                  "   </head>  " +
                                  "     " +
                                  "   <body style='margin:0px; padding:0px;'' bgcolor=' #efefef'>  " +
                                  "       <table align='center' width='700' border='0' cellspacing='0' cellpadding='0' class='em_main_table'  " +
                                  "           style='width:700px;'>  " +
                                  "           <tr>  " +
                                  "               <td style='padding:25px;' class='em_padd' valign='top' bgcolor='#fff' align='center'>  " +
                                  "                   <table width='100%' cellspacing='0' cellpadding='0' border='0' align='center'>  " +
                                  "                       <tbody>  " +
                                  "                           <tr>  " +
                                  "                               <td style='font-family:\"Open Sans\", Arial, sans-serif; font-size:21px; line-height:15px;font-weight: 600; color:#20325F;' valign='top' align='center'>" + practice.name + "</td>  " +
                                  "                           </tr>  " +
                                  "                       </tbody>  " +
                                  "                   </table>  " +
                                  "               </td>  " +
                                  "           </tr>  " +
                                  "           <tr>  " +
                                  "               <td valign='top' align='center'>  " +
                                  "                   <table width='100%' cellspacing='0' cellpadding='0' border='0' align='center'>  " +
                                  "                       <tbody>  " +
                                  "                           <tr>  " +
                                  "                               <td valign='top' align='center'><img class='em_img' alt='hospital_logo'  " +
                                  "                                       style='display:block; font-family:Arial, sans-serif; font-size:30px; line-height:34px; color:#000000; max-width:700px;'  " +
                                  "                                       src='" + practice.serverName + practice.logoPath + "' width='700' border='0' height='190'></td>  " +
                                  "                           </tr>  " +
                                  "                       </tbody>  " +
                                  "                   </table>  " +
                                  "               </td>  " +
                                  "           </tr>  " +
                                  "           <tr>  " +
                                  "               <td valign='top' align='center' bgcolor='#fff' style='padding:35px 70px 30px;' class='em_padd'>  " +
                                  "                   <table align='center' width='100%' border='0' cellspacing='0' cellpadding='0'>  " +
                                  "                       <tr>  " +
                                  "                           <td align='center' valign='top'  " +
                                  "                               style='font-family:\"Open Sans\", Arial, sans-serif; font-size:20px;font-weight: 600; line-height:30px; color:#20325F;'>  " +
                                  "                               Summary report</td>  " +
                                  "                       </tr>  " +
                                  "                       <tr>  " +
                                  "                           <td height='15' style='font-size:0px; line-height:0px; height:15px;'>&nbsp;</td>  " +
                                  "                       </tr>  " +
                                  "                       <tr>  " +
                                  "                           <td align='left' valign='top'  " +
                                  "                               style='font-family:\"Open Sans\", Arial, sans-serif; font-size:16px; line-height:22px;font-weight: 600; color:#000; letter-spacing:2px; padding-bottom:12px;'>  " +
                                  "                               Hi " + patient.name + ",  " +
                                  "                           </td>  " +
                                  "                       </tr>  " +
                                  "                       <tr>  " +
                                  "                           <td height='5' class='em_h20' style='font-size:0px; line-height:0px; height:5px;'>&nbsp;</td>  " +
                                  "                       </tr>  " + adviceList +
                                  "   					 <tr>  "+
                                  "                           <td align='left' valign='top'  " +
                                  "                            style='font-family:\"Open Sans\", Arial, sans-serif; font-size:14px; line-height:22px; color:#666;padding-bottom:12px;'>  " +
                                  "                                <b style='color:#000;'>Advice:</b>&nbsp;" + patient.medication + "</td>  " +
                                  "                       </tr>  " +
                                  "   					 <tr>  "+
                                  "                           <td align='left' valign='top'  " +
                                  "                               style='font-family:\"Open Sans\", Arial, sans-serif; font-size:14px; line-height:22px; color:#666;padding-bottom:12px;'>  " +
                                  "                                <b style='color:#000;'>Follow Up in:</b>&nbsp;" + patient.followUpNumber + "/" + patient.followUpMeasure + "</td>  " +
                                  "                          </tr>  " +
                                  "                          <tr>  " +
                                  "                              <td height='15' class='em_h20' style='font-size:0px; line-height:0px; height:15px;'>&nbsp;</td>  " +
                                  "                          </tr>  " +
                                  "                           " +
                                  "                      </table>  " +
                                  "                  </td>  " +
                                  "              </tr>  " +
                                  "              <tr>  " +
                                  "                  <td valign='top' align='center' bgcolor='#f4f7ff' style='padding:38px 30px;' class='em_padd'>  " +
                                  "                      <table align='center' width='100%' border='0' cellspacing='0' cellpadding='0'>  " +
                                  "                          <tr>  " +
                                  "                              <td align='center' valign='top' colspan='3' style='font-family:\"Open Sans\", Arial, sans-serif; font-size:20px;font-weight: 600; line-height:30px; color:#20325F;'>How Its Work</td>  " +
                                  "                          </tr>  " +
                                  "                          <tr>  " +
                                  "                              <td height='20' class='em_h20' colspan='3' style='font-size:0px; line-height:0px; height:20px;'>&nbsp;</td>  " +
                                  "                          </tr>  " +
                                  "                          <tr>  " +
                                  "                              <td align='center' valign='top'>  " +
                                  "                                  <table align='center' width='100%' border='0' cellspacing='0' cellpadding='0'>  " +
                                  "                                      <tr>  " +
                                  "                                          <td align='center' valign='top'><img src='" + practice.serverName + "/img/Ellipse-34.png'></td>  " +
                                  "                                      </tr>  " +
                                  "                                      <tr>  " +
                                  "                                          <td align='center' valign='top' style='font-family:\"Open Sans\", Arial, sans-serif; font-size:17px;line-height:30px; color:#000;'>Join Conference</td>  " +
                                  "                                      </tr>  " +
                                  "                                  </table>  " +
                                  "                              </td>  " +
                                  "                              <td align='center' valign='top'>  " +
                                  "                                  <table align='center' width='100%' border='0' cellspacing='0' cellpadding='0'>  " +
                                  "                                      <tr>  " +
                                  "                                          <td align='center' valign='top'><img src='" + practice.serverName + "/img/Ellipse-35.png'></td>  " +
                                  "                                      </tr>  " +
                                  "                                      <tr>  " +
                                  "                                          <td align='center' valign='top' style='font-family:\"Open Sans\", Arial, sans-serif; font-size:17px;line-height:24px; color:#000;'>Communicates<br>with Doctor</td>  " +
                                  "                                      </tr>  " +
                                  "                                  </table>  " +
                                  "                              </td>  " +
                                  "                              <td align='center' valign='top'>  " +
                                  "                                  <table align='center' width='100%' border='0' cellspacing='0' cellpadding='0'>  " +
                                  "                                      <tr>  " +
                                  "                                          <td align='center' valign='top'><img src='" + practice.serverName + "/img/Ellipse-36.png'></td>  " +
                                  "                                      </tr>  " +
                                  "                                      <tr>  " +
                                  "                                          <td align='center' valign='top' style='font-family:\"Open Sans\", Arial, sans-serif; font-size:17px;line-height:24px; color:#000;'>chat with doctor<br>to Patient </td>  " +
                                  "                                      </tr>  " +
                                  "                                  </table>  " +
                                  "                              </td>  " +
                                  "                          </tr>  " +
                                  "                      </table>  " +
                                  "                  </td>  " +
                                  "              </tr>  " +
                                  "              <tr>  " +
                                  "                  <td valign='top' align='center' bgcolor='#20325f' style='padding:38px 30px;' class='em_padd'>  " +
                                  "                      <table align='center' width='100%' border='0' cellspacing='0' cellpadding='0'>  " +
                                  "                          <tr>  " +
                                  "                              <td valign='top' align='center' style='padding-bottom:16px;'>  " +
                                  "                                  <table align='center' border='0' cellspacing='0' cellpadding='0'>  " +
                                  "                                      <tr>  " +
                                  "                                          <td valign='top' align='center'><a href='#' target='_blank'  " +
                                  "                                                  style='text-decoration:none;'><img src='" + practice.serverName + "/img/twitter.png' alt='fb'  " +
                                  "                                                      style='display:block; font-family:Arial, sans-serif; font-size:14px; line-height:14px; color:#ffffff; max-width:20px;margin-right: 15px;max-height: 20px;'  " +
                                  "                                                      border='0' width='26' height='26' /></a></td>  " +
                                  "                                          <td width='6' style='width:6px;'>&nbsp;</td>  " +
                                  "                                          <td valign='top' align='center'><a href='#' target='_blank'  " +
                                  "                                                  style='text-decoration:none;'><img src='" + practice.serverName + "/img/linkedin.png' alt='tw'  " +
                                  "                                                      style='display:block; font-family:Arial, sans-serif; font-size:14px; line-height:14px; color:#ffffff; max-width:20px;margin-right: 15px;max-height: 20px'  " +
                                  "                                                      border='0' width='27' height='26' /></a></td>  " +
                                  "                                          <td width='6' style='width:6px;'>&nbsp;</td>  " +
                                  "                                          <td valign='top' align='center'><a href='#' target='_blank'  " +
                                  "                                                  style='text-decoration:none;'><img src='" + practice.serverName + "/img/rss.png' alt='yt'  " +
                                  "                                                      style='display:block; font-family:Arial, sans-serif; font-size:14px; line-height:14px; color:#ffffff; max-width:20px;margin-right: 15px;max-height: 20px'  " +
                                  "                                                      border='0' width='26' height='26' /></a></td>  " +
                                  "                                      </tr>  " +
                                  "                                  </table>  " +
                                  "                              </td>  " +
                                  "                          </tr>  " +
                                  "                          <tr>  " +
                                  "                              <td align='center' valign='top'  " +
                                  "                                  style='font-family:\"Open Sans\", Arial, sans-serif; font-size:11px; line-height:18px; color:#fff;'>  " +
                                  "                                  <a href='#' target='_blank' style='color:#fff; text-decoration:underline;'>PRIVACY  " +
                                  "                                      STATEMENT</a> | <a href='#' target='_blank'  " +
                                  "                                      style='color:#fff; text-decoration:underline;'>TERMS OF SERVICE</a> | <a href='#'  " +
                                  "                                      target='_blank' style='color:#fff; text-decoration:underline;'>RETURNS</a><br />  " +
                                  "                                  &copy; 2020 Fewa Telemedicine. All Rights Reserved.<br />  " +
                                  "                                  If you do not wish to receive any further emails from us, please <a href='#' target='_blank'  " +
                                  "                                      style='text-decoration:none; color:#fff;'>unsubscribe</a></td>  " +
                                  "                          </tr>  " +
                                  "                      </table>  " +
                                  "                  </td>  " +
                                  "              </tr>  " +
                                  "          </table>  " +
                                  "      </body>  " +
                                  "        " +
                                  "     </html>  ";

                var emailSubject = "After Visit Summary Report";
                var msg          = MailHelper.CreateSingleEmail(from, to, emailSubject, practice.emailPlainBody, htmlContent);
                var res          = await client.SendEmailAsync(msg);

                if (res.StatusCode == System.Net.HttpStatusCode.OK || res.StatusCode == System.Net.HttpStatusCode.Accepted)
                {
                    bResponse = true;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"file: MessengerController.cs method: SendEmailAsync() error: {ex.Message} ");
            }
            return(bResponse);
        }
        public async Task <bool> SendOTP(string receiverEmail, string otp, string hostname = "")
        {
            var bResponse = false;
            var name      = "";

            try
            {
                Provider provider = FewaDbContext.providers.Where(a => a.email == receiverEmail || a.userName == receiverEmail).FirstOrDefault();
                if (provider == null)
                {
                    return(false);
                }
                Practice practice = FewaDbContext.practices.Where(a => a.url == provider.practice).FirstOrDefault();
                if (practice == null)
                {
                    return(false);
                }
                if (!string.IsNullOrEmpty(hostname))
                {
                    practice.serverName = hostname;
                }
                name = (!string.IsNullOrEmpty(provider.name))
                    ? ((!string.IsNullOrEmpty(provider.nameTitle) ? provider.nameTitle : "") + provider.name)
                    : provider.email;

                practice.emailPlainBody = "";
                var htmlContent = "   <table align='center' cellpadding='0' cellspacing='0' border='0' width='100%'bgcolor='#f0f0f0'>  " +
                                  "           <tr>  " +
                                  "           <td style='padding: 30px 30px 20px 30px;'>  " +
                                  "               <table cellpadding='0' cellspacing='0' border='0' width='100%' bgcolor='#ffffff' style='margin: auto;'>  " +
                                  "               <tr style='    background-color: #4caf5000;padding: 40px;border: solid 1px;border-radius: 10px;box-shadow: 5px 5px 20px;'>  " +
                                  "                   <td colspan='2' align='center' style='padding: 10px;'>  " +
                                  "                       <a href='" + practice.serverName + "' target='_blank'><img src='" + practice.serverName + practice.logoPath + "' style='max-height: 150px;' border='0' /></a>  " +
                                  "                   </td>  " +
                                  "               </tr>  " +
                                  "               <tr>  " +
                                  "                   <td colspan='2' align='center' style='padding: 50px 50px 0px 50px;'>  " +
                                  "                       <h1 style='padding-right: 0em; margin: 0; line-height: 40px; font-weight:300; font-family: \"Nunito Sans\", Arial, Verdana, Helvetica, sans-serif; color: #666; text-align: left; padding-bottom: 1em;'>  " +
                                  "                           Password Reset  " +
                                  "                       </h1>  " +
                                  "                   </td>  " +
                                  "               </tr>  " +
                                  "               <tr>  " +
                                  "                   <td style='text-align: left; padding: 0px 50px;' valign='top'>  " +
                                  "                       <p style='font-size: 18px; margin: 0; line-height: 24px; font-family: \"Nunito Sans\", Arial, Verdana, Helvetica, sans-serif; color: #666; text-align: left; padding-bottom: 3%;'>  " +
                                  "                           Hi " + name + ",  " +
                                  "                       </p>  " +
                                  "                       <p style='font-size: 18px; margin: 0; line-height: 24px; font-family: \"Nunito Sans\", Arial, Verdana, Helvetica, sans-serif; color: #666; text-align: left; padding-bottom: 3%;'>  " +
                                  "                           Seems like you forgot your password for Fewa Telehealth. If this is true, use below one time password to reset your password.  " +
                                  "                       </p>  " +
                                  "   					<h1 style='padding-right: 0em; margin: 0; line-height: 0px; font-weight:300; font-family: \"Nunito Sans\", Arial, Verdana, Helvetica, sans-serif; color: #666; text-align: center; padding-bottom: 1em; font-size: 25px;'>  "+
                                  "                           " + otp + "  " +
                                  "                       </h1>  " +
                                  "   					<p style='font-size: 18px; margin: 0; line-height: 24px; font-family: \"Nunito Sans\", Arial, Verdana, Helvetica, sans-serif; color: #666; text-align: left; padding-bottom: 3%;'>  "+
                                  "   						<strong>Note:</strong>&nbsp; One time password is case sensitive.<br>  "+
                                  "                           If you did not forgot your password you can safely ignore this email.  " +
                                  "                       </p>  " +
                                  "                   </td>  " +
                                  "               </tr>  " +
                                  "               <tr>  " +
                                  "                   <td style='text-align: left; padding: 30px 50px 50px 50px' valign='top'>  " +
                                  "                       <p style='font-size: 18px; margin: 0; line-height: 24px; font-family: \"Nunito Sans\", Arial, Verdana, Helvetica, sans-serif; color: #505050; text-align: left;'>  " +
                                  "                           Thanks,<br/>Fewa Team  " +
                                  "                       </p>  " +
                                  "                   </td>  " +
                                  "               </tr>  " +
                                  "               <tr>  " +
                                  "                   <td colspan='2' align='center' style='padding: 20px 40px 40px 40px;' bgcolor='#f0f0f0'>  " +
                                  "                       <p style='font-size: 12px; margin: 0; line-height: 24px; font-family: \"Nunito Sans\", Arial, Verdana, Helvetica, sans-serif; color: #777;'>  " +
                                  "                           Powered by &copy; 2020  " +
                                  "                           <a href='" + practice.serverName + "' target='_blank' style='color: #777; text-decoration: none'> Fewa Telehealth</a>  " +
                                  "                       </p>  " +
                                  "                   </td>  " +
                                  "               </tr>  " +
                                  "               </table>  " +
                                  "           </td>  " +
                                  "       </tr>  " +
                                  "  </table>  ";
                practice.emailSubject = "Password verification";
                var client = new SendGridClient(practice.emailApiKey);
                var from   = new EmailAddress(practice.email);
                var to     = new EmailAddress(provider.email);

                var msg = MailHelper.CreateSingleEmail(from, to, practice.emailSubject, practice.emailPlainBody, htmlContent);
                var res = await client.SendEmailAsync(msg);

                if (res.StatusCode == System.Net.HttpStatusCode.OK || res.StatusCode == System.Net.HttpStatusCode.Accepted)
                {
                    bResponse = true;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"file: SecurityController.cs method: SendOtpAsync() error: {ex.Message} ");
            }
            return(bResponse);
        }
        public void WithANullCarbonCopyThenAnExceptionIsThrown()
        {
            var sendGridMessage = MailHelper.CreateSingleEmail(new EmailAddress(), new EmailAddress(), string.Empty, string.Empty, string.Empty);

            Assert.Throws <ArgumentNullException>(() => { sendGridMessage.AddCc(null, 0); });
        }
        public void WithANullListOfCarbonCopiesThenAnExceptionIsThrown()
        {
            var sendGridMessage = MailHelper.CreateSingleEmail(new EmailAddress(), new EmailAddress(), string.Empty, string.Empty, string.Empty);

            Assert.Throws <InvalidOperationException>(() => { sendGridMessage.AddCcs(new List <EmailAddress>()); });
        }
Esempio n. 15
0
        public async Task Email(EmailMembership email)
        {
            var correo = email.Percentage;

            var status = TrueOrFalse(IsAdminHotelRegistered(email.FkHotel));

            var client           = new SendGridClient("sendgrid_key");
            var from             = new EmailAddress("*****@*****.**", "Stay n'Chill");
            var subject          = "Confirmación de Solicitud";
            var to               = new EmailAddress(correo);
            var plainTextContent = "";

            var emailTitle      = "Confirmar solicitud de hotel";
            var emailButtonText = "CONFIRMAR SOLICITUD";
            var emailBody       = "Hola, gracias por solicitar la inscripción de hotel. Para proceder con la confirmación de la solicitud, presione el botón.";
            var emailFooter     = "Presione el botón para confirmar la solicitud de hotel";

            // IF dependiendo si ya tiene 1 hotel o no
            var emailLink = "";

            if (status)
            {
                emailLink = "http://*****:*****@"<body class='full-padding' style='margin: 0;padding: 0;-webkit-text-size-adjust: 100%;'>
<!--<![endif]-->
    <table class='wrapper' style='border-collapse: collapse;table-layout: fixed;min-width: 320px;width: 100%;background-color: #f0f0f0;' cellpadding='0' cellspacing='0' role='presentation'><tbody><tr><td>
      <div role='banner'>
        <div class='preheader' style='Margin: 0 auto;max-width: 560px;min-width: 280px; width: 280px;width: calc(28000% - 167440px);'>
          <div style='border-collapse: collapse;display: table;width: 100%;'>
          <!--[if (mso)|(IE)]><table align='center' class='preheader' cellpadding='0' cellspacing='0' role='presentation'><tr><td style='width: 280px' valign='top'><![endif]-->
            <div class='snippet' style='display: table-cell;Float: left;font-size: 12px;line-height: 19px;max-width: 280px;min-width: 140px; width: 140px;width: calc(14000% - 78120px);padding: 10px 0 5px 0;color: #bdbdbd;font-family: Ubuntu,sans-serif;'>
              
            </div>
          <!--[if (mso)|(IE)]></td><td style='width: 280px' valign='top'><![endif]-->
            <div class='webversion' style='display: table-cell;Float: left;font-size: 12px;line-height: 19px;max-width: 280px;min-width: 139px; width: 139px;width: calc(14100% - 78680px);padding: 10px 0 5px 0;text-align: right;color: #bdbdbd;font-family: Ubuntu,sans-serif;'>
              
            </div>
          <!--[if (mso)|(IE)]></td></tr></table><![endif]-->
          </div>
        </div>
        
      </div>
      <div>
      <div class='layout one-col fixed-width' style='Margin: 0 auto;max-width: 600px;min-width: 320px; width: 320px;width: calc(28000% - 167400px);overflow-wrap: break-word;word-wrap: break-word;word-break: break-word;'>
        <div class='layout__inner' style='border-collapse: collapse;display: table;width: 100%;background-color: #ffffff;' emb-background-style>
        <!--[if (mso)|(IE)]><table align='center' cellpadding='0' cellspacing='0' role='presentation'><tr class='layout-fixed-width' emb-background-style><td style='width: 600px' class='w560'><![endif]-->
          <div class='column' style='text-align: left;color: #787778;font-size: 16px;line-height: 24px;font-family: Ubuntu,sans-serif;max-width: 600px;min-width: 320px; width: 450px;width: calc(28000% - 167400px);'>
        
            <div style='Margin-left: 20px;Margin-right: 20px;Margin-top: 24px;'>
      <div style='mso-line-height-rule: exactly;line-height: 20px;font-size: 1px;'>&nbsp;</div>
    </div>
        
            <div style='Margin-left: 20px;Margin-right: 20px;'>
      <div style='mso-line-height-rule: exactly;mso-text-raise: 4px;'>
        <h1 style='Margin-top: 0;Margin-bottom: 0;font-style: normal;font-weight: normal;color: #565656;font-size: 30px;line-height: 38px;text-align: center;'><strong>" + $@"{emailTitle}" + @"</strong></h1><p style='Margin-top: 20px;Margin-bottom: 20px;'>&nbsp;<br />
" + $@"{emailBody}" + @"</p>
      </div>
    </div>
        
            <div style='Margin-left: 20px;Margin-right: 20px;'>
      <div style='mso-line-height-rule: exactly;line-height: 10px;font-size: 1px;'>&nbsp;</div>
    </div>
        
            <div style='Margin-left: 20px;Margin-right: 20px;'>
      <div class='btn btn--flat btn--large' style='Margin-bottom: 20px;text-align: center;'>
        <![if !mso]><a style='border-radius: 4px;display: inline-block;font-size: 14px;font-weight: bold;line-height: 24px;padding: 12px 24px;text-align: center;text-decoration: none !important;transition: opacity 0.1s ease-in;color: #ffffff !important;background-color: #80bf2e;font-family: Ubuntu, sans-serif;' href='"


                                            + $@"{emailLink}" + @"?id=" + $@"{email.FkHotel}" + @"&Zpi3Lv2kMB0RzGz5TjMSkRJZ1Y7t10I6jpbHhx2pzjMZpi3Lv2kMB0RzGz5TjMSkRJZ1Y7t10I6jpbHhx2pzjM=" + $@"{email.membershipPrice}" + @"'
        
        >" + $@"{emailButtonText}" + @"</a><![endif]>
      <!--[if mso]><p style='line-height:0;margin:0;'>&nbsp;</p><v:roundrect xmlns:v='urn:schemas-microsoft-com:vml' href='http://test.com' style='width:219px' arcsize='9%' fillcolor='#80BF2E' stroke='f'><v:textbox style='mso-fit-shape-to-text:t' inset='0px,11px,0px,11px'><center style='font-size:14px;line-height:24px;color:#FFFFFF;font-family:Ubuntu,sans-serif;font-weight:bold;mso-line-height-rule:exactly;mso-text-raise:4px'>COMPLETE THE<br>
SURVEY</center></v:textbox></v:roundrect><![endif]--></div>
    </div>
        
            <div style='Margin-left: 20px;Margin-right: 20px;'>
      <div style='mso-line-height-rule: exactly;line-height: 10px;font-size: 1px;'>&nbsp;</div>
    </div>
        
            <div style='Margin-left: 20px;Margin-right: 20px;'>
      <div style='mso-line-height-rule: exactly;mso-text-raise: 4px;'>
        <p style='Margin-top: 0;Margin-bottom: 20px;'><em>" + $@"{emailFooter}" + @"</em></p>
      </div>
    </div>
        
            <div style='Margin-left: 20px;Margin-right: 20px;Margin-bottom: 24px;'>
      <div style='mso-line-height-rule: exactly;line-height: 5px;font-size: 1px;'>&nbsp;</div>
    </div>
        
          </div>
        <!--[if (mso)|(IE)]></td></tr></table><![endif]-->
        </div>
      </div>
  
      <div style='line-height:10px;font-size:10px;'>&nbsp;</div>
    </div></td></tr></tbody></table>
  
</body>");
            var msg      = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
            var response = await client.SendEmailAsync(msg);
        }
Esempio n. 16
0
        public ActionResult Payment_Successfull(int?id)
        {
            var order = db.Orders.Find(id);

            try
            {
                order.status = "At warehouse";

                //order tracking
                //db.Order_Trackings.Add(new Order_Tracking()
                //{
                //    order_ID = order.Order_ID,
                //    date = DateTime.Now,
                //    status = "Payment Recieved | Order still at warehouse",
                //    Recipient = ""
                //});
                db.SaveChanges();
                db.Payments.Add(new Payment()
                {
                    Date          = DateTime.Now,
                    Email         = db.Customers.FirstOrDefault(p => p.Email == User.Identity.Name).Email,
                    AmountPaid    = get_order_total(order.Order_ID),
                    PaymentFor    = "Order " + id + " Payment",
                    PaymentMethod = "PayFast Online"
                });
                db.SaveChanges();
                if (db.Order_Addresses.Where(p => p.Order_ID == id) != null)
                {
                    var expected_Date = DateTime.Now.AddDays(2);
                    do
                    {
                        expected_Date = expected_Date.AddDays(1);
                    } while (expected_Date.DayOfWeek.ToString().ToLower() == "sunday" ||
                             expected_Date.DayOfWeek.ToString().ToLower() == "saturday");

                    //Delivery
                }
                db.SaveChanges();
                ViewBag.Items = db.Order_Items.ToList().FindAll(x => x.Order_id == order.Order_ID);

                update_Stock((int)id);

                string table = "<br/>" +
                               "Items in this order<br/>" +
                               "<table>";
                table += "<tr>" +
                         "<th>Item</th>"
                         +
                         "<th>Quantity</th>"
                         +
                         "<th>Price</th>" +
                         "</tr>";
                foreach (var item in (List <Order_Item>)ViewBag.Items)
                {
                    string items = "<tr> " +
                                   "<td>" + item.Item.Name + " </td>" +
                                   "<td>" + item.quantity + " </td>" +
                                   "<td>R " + item.price + " </td>" +
                                   "<tr/>";
                    table += items;
                }

                table += "<tr>" +
                         "<th></th>"
                         +
                         "<th></th>"
                         +
                         "<th>" + get_order_total(order.Order_ID).ToString("R 0.00") + "</th>" +
                         "</tr>";
                table += "</table>";

                var client      = new SendGridClient("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");
                var from        = new EmailAddress("*****@*****.**", "Shopify Here");
                var subject     = "Order " + id + " | Payment Recieved";
                var to          = new EmailAddress(order.Customer.Email, order.Customer.FirstName + " " + order.Customer.LastName);
                var htmlContent = "Hi " + order.Customer.FirstName + ", We recieved your payment, you will have your goodies any time from now " + table;
                var msg         = MailHelper.CreateSingleEmail(from, to, subject, null, htmlContent);
                var response    = client.SendEmailAsync(msg);
            }
            catch (Exception ex) { }

            ViewBag.Order   = order;
            ViewBag.Account = db.Customers.Find(order.Email);
            ViewBag.Address = db.Order_Addresses.ToList().Find(x => x.Order_ID == order.Order_ID);
            ViewBag.Total   = get_order_total(order.Order_ID);
            Pymnt           = true;
            return(View());
        }
Esempio n. 17
0
        private static async Task Main(string[] args)
        {
            IConfiguration config = new ConfigurationBuilder()
                                    .AddJsonFile("appsettings.json", true, true)
                                    .AddUserSecrets <Program>()
                                    .Build();

            try
            {
                var content = File.ReadAllText(config["Email:Body:Path"], Encoding.UTF8);

                List <string> tos = new List <string>();
                if (!string.IsNullOrWhiteSpace(config["Email:Destination:csv"]) && File.Exists(config["Email:Destination:csv"]))
                {
                    using (var reader = new StreamReader(config["Email:Destination:csv"]))
                    {
                        while (!reader.EndOfStream)
                        {
                            var value = reader.ReadLine();
                            if (IsValidEmail(value))
                            {
                                tos.Add(value);
                            }
                        }
                    }
                }
                else
                {
                    tos.Add(config["Email:Destination:To"]);
                }
                var client = new SendGridClient(config["SendGrid:Key"]);

                foreach (var to in tos)
                {
                    try
                    {
                        var msg = MailHelper.CreateSingleEmail(
                            new EmailAddress(config["Email:From"]),
                            new EmailAddress(to),
                            config["Email:Subject"],
                            content,
                            content);

                        var response = await client.SendEmailAsync(msg);

                        Console.WriteLine($"E-mail sent to {to}!");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                }


                Console.WriteLine("The job is done !");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Esempio n. 18
0
        public async Task <string> Send(Email currentEmail, string ticker)
        {
            var AllUsers = _registration.ReturnAll();

            var client           = new SendGridClient("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");
            var from             = new EmailAddress(currentEmail.From);
            var subject          = currentEmail.Subject;
            var plainTextContent = currentEmail.Content;
            var htmlContent      = "<p>" + currentEmail.Content + "</p>";

            if (currentEmail.Admin)
            {
                foreach (var recipiant in AllUsers)
                {
                    if (recipiant.Admin)
                    {
                        var to       = new EmailAddress(recipiant.Email);
                        var msg      = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
                        var response = await client.SendEmailAsync(msg);
                    }
                }
                return("sent");
            }

            else if (currentEmail.UpFive)
            {
                foreach (var recipiant in AllUsers)
                {
                    if (recipiant.UpFive)
                    {
                        foreach (var Ticker in recipiant.Stocks)
                        {
                            if (Ticker.stock == ticker)
                            {
                                var to       = new EmailAddress(recipiant.Email);
                                var msg      = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
                                var response = await client.SendEmailAsync(msg);
                            }
                        }
                    }
                }
                return("sent");
            }

            else if (currentEmail.DownFive)
            {
                foreach (var recipiant in AllUsers)
                {
                    if (recipiant.DownFive)
                    {
                        foreach (var Ticker in recipiant.Stocks)
                        {
                            if (Ticker.stock == ticker)
                            {
                                var to       = new EmailAddress(recipiant.Email);
                                var msg      = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
                                var response = await client.SendEmailAsync(msg);
                            }
                        }
                    }
                }
                return("sent");
            }

            else if (currentEmail.MovingAvg)
            {
                foreach (var recipiant in AllUsers)
                {
                    if (recipiant.MovingAvg)
                    {
                        foreach (var Ticker in recipiant.Stocks)
                        {
                            if (Ticker.stock == ticker)
                            {
                                var to       = new EmailAddress(recipiant.Email);
                                var msg      = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
                                var response = await client.SendEmailAsync(msg);
                            }
                        }
                    }
                }
                return("sent");
            }
            else
            {
                return("error");
            }
        }
Esempio n. 19
0
        public async Task <SendEmailResponse> SendEmailAsync(SendEmailDetails details)
        {
            ///<summary>
            ///Api generada en SendGrid
            /// </summary>
            var apiKey = _config["SendGridKey"];
            ///<summary>
            ///Clase SendGridClient que requiere como parámetros apiKey
            ///Posee 4 sobrecargas para más información navegar dentro de la clase.
            /// </summary>
            var client = new SendGridClient(apiKey);
            //From
            var from = new EmailAddress(details.FromEmail, details.FromName);
            //Subject
            var subject = details.Subject;
            //To
            var to = new EmailAddress(details.ToEmail, details.ToName);
            //Content
            var plainTextContent = details.BodyContent;
            //Crea la clase email lista para enviar
            var msg = MailHelper.CreateSingleEmail(from,
                                                   to,
                                                   subject,
                                                   //Texto plano
                                                   plainTextContent,
                                                   //Html content
                                                   details.IsHtml ?
                                                   details.BodyContent :
                                                   null);


            var response = await client.SendEmailAsync(msg);

            ///<summary>
            ///Si el mail es aceptado exitosamente
            /// </summary>

            if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
            {
                return(new SendEmailResponse());
            }

            ///<summary>
            ///De lo contrario se ejecutará la respuesta al error
            /// </summary>
            try
            {
                var bodyResult = await response.Body.ReadAsStringAsync();

                //Deserializar la respuesta

                var sendGridResponse = JsonConvert.DeserializeObject <SendGridResponse>(bodyResult);

                //Agregar errores a la lista
                var errorResponse = new SendEmailResponse
                {
                    Errors = sendGridResponse?.Errores.Select(x => x.Message).ToList()
                };

                //Asegurarnos de tener aunque sea un error

                if (errorResponse.Errors == null || errorResponse.Errors.Count == 0)
                {
                    //Agregar un error desconocido
                    errorResponse.Errors = new List <string>(new[] { "Ocurrió un error desconocido. Por favor contacte con soporte" });
                }
            }
            catch (Exception ex)
            {
                //


                //Rompe si estamos debuggeando

                if (Debugger.IsAttached)
                {
                    var error = ex;
                    Debugger.Break();
                }


                //Si ocurre algo inesperado devuelve el mensaje
                return(new SendEmailResponse
                {
                    Errors = new List <string>(new[] { "Ocurrió un error inesperado" })
                });
            }


            return(new SendEmailResponse());
        }
Esempio n. 20
0
        private async Task SendApproveConfirmEmailAsync(long ticketId)
        {
            var confirmInfo = DataAccess.GetApproveConfirmInfo(ticketId);

            var client = new SendGridClient(ConfigurationManager.AppSettings["SendGridApiKey"]);
            var from   = new EmailAddress("*****@*****.**", "Poolu");
            var to     = new EmailAddress(confirmInfo.UserEmail);
            var title  = confirmInfo.PoolName + " ticket approved";

            var message = new System.Text.StringBuilder();

            message.Append("<html><body>");

            message.Append("Congratulations " + confirmInfo.UserName + ",");
            message.Append("<br></br>");

            message.Append("<br>");
            message.Append("Your ticket has been approved for the ");
            message.Append(confirmInfo.PoolName);
            message.Append(" lottery pool drawing on ");
            message.Append(confirmInfo.DrawDate);
            message.Append(" at 11pm EST.");
            message.Append("</br><br></br>");

            message.Append("<br>");
            message.Append("Lottery Number:&nbsp;&nbsp;");

            if (confirmInfo.LotteryNumbers.Count > 1)
            {
                foreach (var num in confirmInfo.LotteryNumbers)
                {
                    message.Append("<br>");
                    message.Append("&nbsp;&nbsp;&nbsp;&nbsp;");
                    message.Append(AddSpaceToLotteryNumbers(num));
                    message.Append("</br>");
                }
                message.Append("</br><br></br>");
            }
            else
            {
                message.Append(AddSpaceToLotteryNumbers(confirmInfo.LotteryNumbers[0]));
                message.Append("</br>");
            }

            message.Append("<br>");
            message.Append("Lottery Game:&nbsp;&nbsp;");
            message.Append(confirmInfo.PoolName);
            message.Append("</br>");

            message.Append("<br>");
            message.Append("Draw Date:&nbsp;&nbsp;");
            message.Append(confirmInfo.DrawDate);
            message.Append("</br><br></br>");

            message.Append("<br>Thanks,</br>");
            message.Append("<br></br>");

            message.Append("<br>");
            message.Append("The Poolu Team");
            message.Append("</br><br></br>");

            message.Append("</body></html>");

            var msg = MailHelper.CreateSingleEmail(from, to, title, "", message.ToString());

            var response = await client.SendEmailAsync(msg);
        }
Esempio n. 21
0
        //Refund One Ticket
        public void SendEmailRefundForBuyerOneTicket(int ticketId)
        {
            try
            {
                var    apiKey             = SETTING.Value.SendGridKey;
                var    client             = new SendGridClient(apiKey);
                string emailTemplateHtml  = _hostingEnvironment.ContentRootPath + "\\EmailTemplate\\EmailTemplateRefund.html";
                string ticketTemplatehtml = _hostingEnvironment.ContentRootPath + "\\EmailTemplate\\TicketsTemplate.html";
                string body      = string.Empty;
                string ticketRow = string.Empty;
                var    ticket    = _ticketRepository.Get(r => r.Id == ticketId);
                var    customer  = _customerRepository.Get(c => c.Id == ticket.BuyerId);
                //using streamreader for reading my htmltemplate
                using (StreamReader reader = new StreamReader(emailTemplateHtml))
                {
                    body = reader.ReadToEnd();
                }
                var customerEmail      = customer.Email;
                var customerName       = customer.FullName;
                var customerPhone      = customer.PhoneNumber;
                var ticketCode         = ticket.TicketCode;
                var totalAmount        = ticket.SellingPrice;
                var date               = DateTime.UtcNow;
                var ticketRowViewModel = _mapper.Map <Ticket, TicketRowViewModel>(ticket);

                //replacing the required things
                body = body.Replace("{customerName}", customerName);
                body = body.Replace("{subTotal}", totalAmount.ToString());
                body = body.Replace("{Total}", totalAmount.ToString());

                body = body.Replace("{refundTitle}", SETTING.Value.RefundTitle);
                body = body.Replace("{fromName}", SETTING.Value.FromName);

                using (StreamReader reader = new StreamReader(ticketTemplatehtml))
                {
                    ticketRow = reader.ReadToEnd();
                    var departureStation = _stationRepository.Get(s => s.Id == ticketRowViewModel.DepartureStationId).Name;
                    var arrivalStation   = _stationRepository.Get(s => s.Id == ticketRowViewModel.ArrivalStationId).Name;
                    ticketRow = ticketRow.Replace("{ticketCode}", ticketRowViewModel.TicketCode);
                    ticketRow = ticketRow.Replace("{Description}", ticketRowViewModel.Description);
                    ticketRow = ticketRow.Replace("{departureCity}", ticketRowViewModel.DepartureCity);
                    ticketRow = ticketRow.Replace("{departureStation}", departureStation);
                    ticketRow = ticketRow.Replace("{departureTime}", ticketRowViewModel.DepartureDateTime.ToString());
                    ticketRow = ticketRow.Replace("{arrivalCity}", ticketRowViewModel.ArrivalCity);
                    ticketRow = ticketRow.Replace("{arrivalStation}", arrivalStation);
                    ticketRow = ticketRow.Replace("{arrivalTime}", ticketRowViewModel.ArrivalDateTime.ToString());
                    ticketRow = ticketRow.Replace("{Amount}", ticketRowViewModel.SellingPrice.ToString());
                }
                body = body.Replace("{ticketList}", ticketRow);

                var from             = new EmailAddress(SETTING.Value.FromEmail, SETTING.Value.FromName);
                var subject          = ticketCode + " - Receipt - Refund";
                var to               = new EmailAddress(customerEmail, customerName);
                var plainTextContent = "";
                var htmlContent      = body;
                var msg              = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
                client.SendEmailAsync(msg);
            }
            catch (Exception)
            {
            }
        }
Esempio n. 22
0
        public async Task <SendEmailResponse> SendEmailAsync(SendEmailDetails details)
        {
            // Get the SendGrid key
            var apiKey = _configuration["AppSettings:SENDGRID_API_KEY"];;

            // Create a new SendGrid client
            var client = new SendGridClient(apiKey);

            // From
            var from = new EmailAddress(details.FromEmail, details.FromName);

            // To
            var to = new EmailAddress(details.ToEmail, details.ToName);

            // Subject
            var subject = details.Subject;

            // Content
            var content = details.Content;

            // Create Email class ready to send
            var msg = MailHelper.CreateSingleEmail(
                from,
                to,
                subject,
                // Plain content
                details.IsHTML ? null : details.Content,
                // HTML content
                details.IsHTML ? details.Content : null);

            // Finally, send the email...
            var response = await client.SendEmailAsync(msg);

            // If we succeeded...
            if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
            {
                // Return successful response
                return(new SendEmailResponse());
            }

            // Otherwise, it failed...

            try
            {
                // Get the result in the body
                var bodyResult = await response.Body.ReadAsStringAsync();

                // Deserialize the response
                var sendGridResponse = JsonConvert.DeserializeObject <SendGridResponse>(bodyResult);

                // Add any errors to the response
                var errorResponse = new SendEmailResponse
                {
                    Errors = sendGridResponse?.Errors.Select(f => f.Message).ToList()
                };

                // Make sure we have at least one error
                if (errorResponse.Errors == null || errorResponse.Errors.Count == 0)
                {
                    // Add an unknown error
                    // TODO: Localization
                    errorResponse.Errors = new List <string>(new[] { "Unknown error from email sending service. Please contact Fasetto support." });
                }

                // Return the response
                return(errorResponse);
            }
            catch (Exception ex)
            {
                // TODO: Localization

                // Break if we are debugging
                if (Debugger.IsAttached)
                {
                    var error = ex;
                    Debugger.Break();
                }

                // If something unexpected happened, return message
                return(new SendEmailResponse
                {
                    Errors = new List <string>(new[] { "Unknown error occurred" })
                });
            }
        }
Esempio n. 23
0
        public async Task <ActionResult> Create([Bind("Id, FirstName, LastName, PhoneNumber, EmailAddress, ContactAgreement, CvUrl, File, State, JobOffer, Candidate")] Application model)
        {
            Role role = await AuthorizationTools.GetRoleAsync(User, _context);

            ViewData.Add("role", role);
            ViewData.Add("id", AuthorizationTools.GetUserDbId(User, _context, role));

            if (role != Role.CANDIDATE)
            {
                return(new UnauthorizedResult());
            }
            JobOffer  offer     = _context.JobOffers.Include(x => x.HR).Where(o => o.Id == model.Id).First();
            string    email     = AuthorizationTools.GetEmail(User);
            Candidate candidate = _context.Candidates.Where(c => c.EmailAddress == email).First();

            if (!ModelState.IsValid)
            {
                return(View());
            }

            var  uploads = Path.Combine(_env.WebRootPath, "uploads");
            bool exists  = Directory.Exists(uploads);

            if (!exists)
            {
                Directory.CreateDirectory(uploads);
            }
            var    fileName   = Path.GetFileName(model.File.FileName);
            var    fileStream = new FileStream(Path.Combine(uploads, model.File.FileName), FileMode.Create);
            string mimeType   = model.File.ContentType;

            byte[] fileData = null;
            using (var memoryStream = new MemoryStream())
            {
                model.File.CopyTo(memoryStream);
                fileData = memoryStream.ToArray();
            }
            model.CvUrl = _blob.UploadFileToBlob(model.File.FileName, fileData, mimeType);

            Application application = new Application()
            {
                FirstName        = model.FirstName,
                LastName         = model.LastName,
                EmailAddress     = model.EmailAddress,
                PhoneNumber      = model.PhoneNumber,
                CvUrl            = model.CvUrl,
                ContactAgreement = model.ContactAgreement,
                Comments         = model.Comments,
                Candidate        = candidate,
                JobOffer         = offer,
                State            = "Pending"
            };


            await _context.JobApplications.AddAsync(application);

            await _context.SaveChangesAsync();

            var apiKey           = "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";
            var client           = new SendGridClient(apiKey);
            var from             = new EmailAddress("*****@*****.**", "HRMiniApp");
            var subject          = "New application";
            var to               = new EmailAddress(offer.HR.EmailAddress);
            var plainTextContent = "";
            var htmlContent      = $"<strong>Your Job Offer received new Application: <a href=https://localhost:5001/Application/Details/{ model.Id}>link</a> </strong>";
            var msg              = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
            var attachment       = new Attachment()
            {
                Content  = Convert.ToBase64String(fileData),
                Filename = "cv.pdf"
            };

            msg.AddAttachment(attachment);
            var response = await client.SendEmailAsync(msg);

            return(RedirectToAction("Index"));
        }
Esempio n. 24
0
        public void sendmail(Guest g, string m)
        {
            //var body = "<p><b> Dear {0}, </b></p><br><p>" +
            //"It's your turn to enter the " + HttpContext.Application["EventName"].ToString() +
            //        "! Please bring this message to the ticket booth. Enjoy the haunt!";
            //var message = new MailMessage();
            //string mailid = g.email;


            //message.To.Add(new MailAddress(mailid));


            //message.From = new MailAddress(HttpContext.Application["Email"].ToString());  // replace with valid value
            //message.Subject = " Now its your turn for event " + HttpContext.Application["EventName"].ToString();
            //message.Body = string.Format(body, g.guestName);
            //message.IsBodyHtml = true;

            //using (var smtp = new SmtpClient())
            //{
            //    var credential = new NetworkCredential
            //    {
            //        UserName = HttpContext.Application["Email"].ToString(),  // replace with valid value
            //        Password = HttpContext.Application["EmailPass"].ToString()  // replace with valid value
            //    };
            //    smtp.Credentials = credential;
            //    smtp.Host = "smtp.gmail.com";
            //    smtp.Port = 587;
            //    smtp.EnableSsl = true;
            //    try
            //    {
            //        smtp.Send(message);
            //        return true;
            //    }
            //    catch (Exception es)
            //    {
            //        Debug.WriteLine("ERROR:" + es.Message);
            //        Debug.WriteLine("To:" + mailid + " From:" + HttpContext.Application["Email"].ToString() + " " + HttpContext.Application["EmailPass"].ToString());
            //        return false;
            //    }
            //}


            var client           = new SendGridClient(HttpContext.Application["SendGridAPIKey"].ToString());
            var from             = new EmailAddress(HttpContext.Application["Email"].ToString(), HttpContext.Application["EventName"].ToString());
            var subject          = "Alert from " + HttpContext.Application["EventName"].ToString();
            var to               = new EmailAddress(g.email, g.guestName);
            var htmlContent      = "";
            var plainTextContent = m;
            var msg              = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);

            Debug.WriteLine("Before sending mail");
            var response = client.SendEmailAsync(msg);

            Debug.WriteLine("After sending mail");
            Debug.WriteLine("OUTSIDE IF:" + response.Result.StatusCode.ToString());
            if (response.Result.StatusCode.ToString() == "Accepted")
            {
                Debug.WriteLine("After sending mail inside message : " + response.Result.StatusCode.ToString());
                //Debug.WriteLine("After sending mail inside if");
                mailstatus = true;
            }
            Debug.WriteLine("After sending mail outside if");
        }
Esempio n. 25
0
 public SendGridMessage ConstroiMensagem()
 {
     return(MailHelper.CreateSingleEmail(From, To, Subject, PlainTextContent, HtmlContent));
 }
Esempio n. 26
0
        public async Task <IHttpActionResult> ForgotPassword([FromBody] string email)
        {
            try
            {
                var result = this._authenticationRepository.FindUserExists(email);

                //here need to check if user verified or not?
                if (result == 0)
                {
                    return(Json(HttpStatusCode.NotFound));
                }

                User user = this._authenticationRepository.FindUserByUserName(email);
                if (user != null && user.EmailConfirmed == false)
                {
                    return(Json(HttpStatusCode.NotFound));
                }

                int            _min         = 1000;
                int            _max         = 9999;
                Random         _rdm         = new Random();
                var            OTP          = _rdm.Next(_min, _max);
                string         returnString = "";
                ForgotPassword model        = new ForgotPassword();
                model.Email = email;
                model.OTP   = OTP.ToString();


                var result1 = this._authenticationRepository.ForgotPassword(model);

                if (result1 > 0)
                {
                    //code otp saved in db  .ge
                    // SmtpSetting smtpSetting = this._authenticationRepository.GetDbContext().SmtpSettings.FirstOrDefault();
                    if (true)
                    {
                        string emailContent = ""; //we need to get this email content from client

                        string passwordResetToken = await this._authenticationRepository.GeneratePasswordResetTokenAsync(result);

                        emailContent = "your Password reset code: " + OTP;

                        //emailContent += string.Format("<br>Password reset Url : <a target='_blank' href='{0}/reset_password?token={1}'>Click here to reset password</a>", this.Request.RequestUri.Host, passwordResetToken);
                        string webSiteUrl = System.Configuration.ConfigurationManager.AppSettings["WebSiteUrl"];

                        emailContent += string.Format("<br><b>Enter above reset code by clicking  </b> : <a target='_blank' href='{0}/VarificationCode'>Verify Code Url</a> Or <br></br> Using Verify code link {1}.", webSiteUrl, webSiteUrl + "/VarificationCode");

                        //string error = string.Empty;
                        //EmailService emailService = new EmailService();
                        //emailService.SendEmail(smtpSetting, "Password reset code for Cervitt", emailContent, email, "", "", out error);


                        string          apiKey         = SENDGRID_API_KEY;
                        SendGridClient  sendGridClient = new SendGridClient(apiKey, "https://api.sendgrid.com");
                        EmailAddress    emailSender    = new EmailAddress("*****@*****.**", "Cervitt");
                        String          subject        = "Password reset code for Cervitt account.";
                        EmailAddress    emailRecipient = new EmailAddress(email);
                        Content         content        = new Content("text/html", emailContent);
                        SendGridMessage mail           = MailHelper.CreateSingleEmail(emailSender, emailRecipient, subject, "", emailContent);

                        //mail.TemplateId = "7f2e9773-771d-47e2-b254-c0ea601da608";
                        //mail.AddSubstitution("<%userId%>", registerUserDTO.NewUserID.ToString());
                        //mail.AddSubstitution("<%confirmationToken%>", HttpServerUtility.UrlTokenEncode(emailConfirmationTokenBytes));

                        dynamic response = sendGridClient.SendEmailAsync(mail);
                    }
                }

                return(Ok());
            }
            catch (Exception ex)
            {
                return(Json(HttpStatusCode.NotFound));
            }
        }
Esempio n. 27
0
        public async void AutomatedEmailSending(User user)
        {
            try
            {
                EmailClient eClient = new EmailClient();
                if (string.IsNullOrEmpty(user.ApiKey))
                {
                    return;
                }
                SendGridClient client = new SendGridClient(eClient.SetEnvironmentVar(user));

                using (StudentDBDataContext con = new StudentDBDataContext(conn_str))
                {
                    var activity = con.GetTable <Activity>().Where(chck => chck.IdUser == user.Id);

                    /// Zoskupenie aktivit na zaklade mena aktivity a datumu odovzdania. aby sa mohli odosielat presne emaily, a iba tam, kde,
                    /// bolo oznacene odosielanie emailovych  upozorneni.
                    var selectActivity = from act in activity
                                         where act.IdUser == user.Id && act.EmailSendingActive == true || act.SendMe == true
                                         group act by new { act.Deadline, act.ActivityName };

                    if (selectActivity == null || selectActivity.Count() <= 0)
                    {
                        return;
                    }

                    ///Prehladavanie kazdej skupiny
                    foreach (var group in selectActivity)
                    {
                        // Prehladavanie jednotlivych aktivit v skupine, aby sme zistili ci ma student dostat upozornenie
                        foreach (var act in group)
                        {
                            var days = ((act.Deadline.Subtract(DateTime.Now).TotalDays));

                            switch (act.EmailSendingActive)
                            {
                            /// Odosielanie prvych upozorneni ak do odovzdania zostavaju 3 alebo 2 dni
                            case true when days <= 3 && days > 1 && act.SendFirst == true && act.Hodnotene == false:
                            {
                                firstReminderAddresses.Add(MailHelper.StringToEmailAddress(act.Student.Email));
                                Activity currAct = con.GetTable <Activity>().Where(x => x.Id == act.Id).FirstOrDefault();
                                currAct.SendFirst = false;
                                con.SubmitChanges(ConflictMode.ContinueOnConflict);
                                break;
                            }
                            /// Zbieranie emailovych adries na odoslanie druhych upozorneni ak do odovzdania zostavaju 1 alebo 0 dni

                            case true when days >= 0 && days < 1 && act.SendSecond == true && act.Hodnotene == false:
                            {
                                secondReminderAddresses.Add(MailHelper.StringToEmailAddress(act.Student.Email));
                                Activity currAct = con.GetTable <Activity>().Where(x => x.Id == act.Id).FirstOrDefault();
                                currAct.SendSecond         = false;
                                currAct.EmailSendingActive = false;
                                con.SubmitChanges(ConflictMode.ContinueOnConflict);
                                break;
                            }

                            default:
                                break;
                            }


                            if (act.SendMe == true && act.Hodnotene == false && days <= 0)
                            {
                                Activity currAct = con.GetTable <Activity>().Where(x => x.Id == act.Id).FirstOrDefault();
                                currAct.SendMe = false;
                                con.SubmitChanges();
                                SendToMe = true;
                                activitiesToGrade.Add(act.ActivityName);
                                groupsToSend.Add(act.StudentSkupina.Nazov);
                            }
                        }

                        /// Ziskanie emailu, ktory ma byt odoslany pre konkretnu aktivitu
                        if (firstReminderAddresses.Count >= 1)
                        {
                            var emailToSend = group.Select(x => x.IdFirstRem);
                            var template    = con.GetTable <EmailTemplate>().Where(x => x.IdUser == user.Id && x.Id == emailToSend.FirstOrDefault()).FirstOrDefault();
                            await SendEmails(template, 3, firstReminderAddresses, user, group.Key.Deadline);
                        }
                        if (secondReminderAddresses.Count >= 1)
                        {
                            var emailToSend = group.Select(x => x.IdSecRem);
                            var template    = con.GetTable <EmailTemplate>().Where(x => x.IdUser == user.Id && x.Id == emailToSend.FirstOrDefault()).FirstOrDefault();
                            await SendEmails(template, 1, secondReminderAddresses, user, group.Key.Deadline);
                        }
                    }


                    if (SendToMe == true)
                    {
                        string activities = string.Empty;
                        string groups     = string.Empty;
                        foreach (var group in groupsToSend.Distinct())
                        {
                            groups = groups + group + ", ";
                        }
                        foreach (var activ in activitiesToGrade.Distinct())
                        {
                            activities += (activ + ", <br/>");
                        }

                        string finalMsg = $"Uplynul dátum odovzdania pre následujúce aktivity: {activities}<br/>";
                        string subject  = $"Aktivita pripravená na hodnotenie pre skupiny: {groups}";
                        var    msg      = MailHelper.CreateSingleEmail(MailHelper.StringToEmailAddress(user.Email), MailHelper.StringToEmailAddress(user.Email)
                                                                       , subject, finalMsg, finalMsg);
                        var result = await client.SendEmailAsync(msg);

                        SendToMe = false;
                    }
                }
            }
            catch (Exception ex)
            {
                Logger newLog = new Logger();
                newLog.LogError(ex);
                return;
            }
        }
Esempio n. 28
0
        public ActionResult PaymentSuccessfull(int?id)
        {
            var order = db.Orders.Find(id);

            try
            {
                db.Payments.Add(new Payment()
                {
                    Date          = DateTime.Now,
                    Email         = db.Customers.FirstOrDefault(p => p.Email == User.Identity.Name).Email,
                    AmountPaid    = getordertotal(Convert.ToInt32(order.OrderID)),
                    PaymentFor    = "Transaction " + id + " Payment",
                    PaymentMethod = "PayFast Online"
                });
                db.SaveChanges();
                ViewBag.Items = db.orderItems.ToList().FindAll(x => x.OrderId == order.OrderID);

                update_Stock((int)id);

                string table = "<br/>" +
                               "Items in this order<br/>" +
                               "<table>";
                table += "<tr>" +
                         "<th>Item</th>"
                         +
                         "<th>Quantity</th>"
                         +
                         "<th>Price</th>" +
                         "</tr>";
                foreach (var item in (List <OrderItem>)ViewBag.Items)
                {
                    string items = "<tr> " +
                                   "<td>" + item.Item.Name + " </td>" +
                                   "<td>" + item.Quantity + " </td>" +
                                   "<td>R " + item.Price + " </td>" +
                                   "<tr/>";
                    table += items;
                }

                table += "<tr>" +
                         "<th></th>"
                         +
                         "<th></th>"
                         +
                         "<th>" + getordertotal(Convert.ToInt32(order.OrderID)).ToString("R 0.00") + "</th>" +
                         "</tr>";
                table += "</table>";

                var client      = new SendGridClient("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");
                var from        = new EmailAddress("*****@*****.**", "MontClair Veterinary");
                var subject     = "Order " + id + " | Payment Recieved";
                var to          = new EmailAddress(order.Customer.Email, order.Customer.FirstName + " " + order.Customer.LastName);
                var htmlContent = "Hi " + order.Customer.FirstName + ", We recieved your payment, you will have your goodies any time from now " + table;
                var msg         = MailHelper.CreateSingleEmail(from, to, subject, null, htmlContent);
                var response    = client.SendEmailAsync(msg);
            }
            catch (Exception ex) { }

            ViewBag.Order   = order;
            ViewBag.Account = db.Customers.Find(order.customerId);
            ViewBag.Address = db.orderAddresses.ToList().Find(x => x.OrderIDs == order.OrderID);
            ViewBag.Total   = getordertotal(Convert.ToInt32(order.OrderID));

            return(View());
        }
Esempio n. 29
0
 public async Task SendEmail(EmailDto emailDto)
 {
     var msg      = MailHelper.CreateSingleEmail(emailDto.From, emailDto.To, emailDto.Subject, "", emailDto.HtmlContent);
     var response = await _emailClient.SendEmailAsync(msg);
 }
Esempio n. 30
0
        static void Main(string[] args)
        {
            try
            {
                bool stop    = false;
                bool stopped = true;

                Dapper.DefaultTypeMap.MatchNamesWithUnderscores = true;

                Task emailEngine = Task.Run(() =>
                {
                    try
                    {
                        stopped = false;

                        while (!stop)
                        {
                            IEnumerable <EmailRequest> requests = null;

                            foreach (var dbCfgConn in ConfigurationManager.ConnectionStrings.Cast <ConnectionStringSettings>().Skip(1))
                            {
                                using (var dbConn = new SqlConnection(dbCfgConn.ConnectionString))
                                {
                                    Console.WriteLine($"Gathering data from {dbConn.DataSource}.{dbConn.Database}....");

                                    requests = dbConn.Query <EmailRequest>(sql: "GetEmailRequests", commandType: CommandType.StoredProcedure);

                                    foreach (var emailReq in requests)
                                    {
                                        Console.WriteLine($"Building Email Request #{emailReq.Id}.......");

                                        var toAddress        = new EmailAddress(emailReq.ToAddress);
                                        var fromAddress      = new EmailAddress(emailReq.FromAddress);
                                        var subject          = emailReq.Subject;
                                        var plainTextContent = string.Empty;
                                        var htmlContent      = emailReq.HtmlBody;

                                        var msg = MailHelper.CreateSingleEmail(fromAddress, toAddress, subject, plainTextContent, htmlContent);

                                        Console.WriteLine($"Sending Email Request #{emailReq.Id} from {emailReq.FromAddress} to {emailReq.ToAddress}.");

                                        bool sent            = false;
                                        string statusMessage = null;

                                        try
                                        {
                                            var response = SendEmail(msg).Result;

                                            sent = true;

                                            if (response.StatusCode != System.Net.HttpStatusCode.Accepted && response.StatusCode != System.Net.HttpStatusCode.OK)
                                            {
                                                string jsonStr = response.Body.ReadAsStringAsync().Result;
                                                var resObj     = JsonConvert.DeserializeObject(jsonStr);

                                                statusMessage = $"ERROR - {{{response.StatusCode}}}: {resObj.ToString()}";

                                                Console.WriteLine($"Error sending email request #{emailReq.Id}.");
                                                Console.WriteLine($"Status --> {statusMessage}");
                                            }
                                            else
                                            {
                                                Console.WriteLine($"Email request #{emailReq.Id} has been sent.");
                                            }
                                        }
                                        finally
                                        {
                                            var paramters = new DynamicParameters();

                                            paramters.Add("@sent", sent, DbType.Boolean, ParameterDirection.Input);
                                            paramters.Add("@id", emailReq.Id, DbType.Int32, ParameterDirection.Input);
                                            paramters.Add("@status_message", statusMessage, DbType.String, ParameterDirection.Input);

                                            dbConn.Execute(sql: "UpsertEmailRequest", param: paramters, commandType: CommandType.StoredProcedure);
                                        }

                                        if (stop)
                                        {
                                            break;
                                        }
                                    }
                                }
                            }

                            Console.WriteLine($"Sleeping {{{DateTime.Now.ToLongTimeString()}}}....");

                            DateTime end = DateTime.Now.AddMilliseconds(TimeSpan.FromMilliseconds(60000).TotalMilliseconds);

                            while (DateTime.Now < end && !stop)
                            {
                                Thread.Sleep(500);
                            }
                        }
                    }
                    catch (Exception exc)
                    {
                        Console.WriteLine("----------------------------------------");
                        Console.WriteLine("Fatal Exception - Shut down main thread.");
                        Console.WriteLine("----------------------------------------");
                        Console.WriteLine(exc.Message);
                        Console.WriteLine("----------------------------------------");
                    }
                    finally
                    {
                        stopped = true;
                    }
                });

                Console.ReadLine();

                stop = true;

                while (!stopped)
                {
                    Thread.Sleep(100);
                }

                Console.WriteLine("The processor is done.");
            }
            catch (Exception exc)
            {
                Console.WriteLine();
                Console.WriteLine("*********************************");
                Console.WriteLine(exc.Message);
                Console.WriteLine();
                Console.WriteLine(exc.ToString());
                Console.WriteLine("*********************************");
            }
            finally
            {
                Console.WriteLine();
                Console.Write("Done.  Presee <Enter> to close the application.");
                Console.ReadLine();
            }
        }