public static void SendMail(string address, string subject, string messageBody, ref string errorMessage)
        {
            try
            {
                var    mailInformation = MailInformation.GetInformation();
                var    fromAddress     = new MailAddress(mailInformation.Address);
                var    toAddress       = new MailAddress(address);
                string fromPassword    = mailInformation.Password;

                var smtp = new SmtpClient();
                smtp.Host                  = mailInformation.Host;
                smtp.Port                  = mailInformation.Port;
                smtp.EnableSsl             = mailInformation.EnableSSL;
                smtp.DeliveryMethod        = SmtpDeliveryMethod.Network;
                smtp.UseDefaultCredentials = false;
                smtp.Credentials           = new NetworkCredential(mailInformation.Address, fromPassword);

                var message = new MailMessage();
                message.From = fromAddress;
                message.To.Add(toAddress);
                message.Subject = subject;
                message.Body    = messageBody;
                smtp.Send(message);
            }
            catch (Exception ex)
            {
                errorMessage = ex.StackTrace;
            }
        }
Beispiel #2
0
        void ReadSettingsForMail()
        {
            string webRootPath = _hostingEnvironment.WebRootPath + @"/mailInformation.json";
            var    JSON        = File.ReadAllText(webRootPath);

            _mailInformation = JsonConvert.DeserializeObject <MailInformation>(JSON);
        }
Beispiel #3
0
        void EmailSendInBackground(object MailInf)
        {
            SendMailDO      sendmailDO = new SendMailDO();
            SendMailModel   sendModel  = new SendMailModel();
            MailInformation MailInform = (MailInformation)MailInf;

            try
            {
                //MailInform.CustomerEmailAddress = "*****@*****.**";
                //MailInform.CustomerEmailAddress = "*****@*****.**";
                string ErrorMessage = "";
                if (MailInform.MailProperties.EmailSender(MailInform.MailProperties.UserName, MailInform.CustomerEmailAddress, MailInform.Subject, MailInform.EmailText, true, 0, ref ErrorMessage))
                {
                    sendModel.Status = true;
                    sendModel.Error  = string.Empty;
                    Insert(sendModel, MailInform, sendmailDO);
                    Console.WriteLine("Deposite Number : " + MailInform.DepositeNumber + " Message send to : " + MailInform.CustomerEmailAddress + " , Success");
                }
                else
                {
                    sendModel.Status = false;
                    sendModel.Error  = ErrorMessage;
                    Insert(sendModel, MailInform, sendmailDO);
                    Console.WriteLine("Deposite Number : " + MailInform.DepositeNumber + " Message Dont send to : " + MailInform.CustomerEmailAddress + " , Error : " + ErrorMessage);
                }
            }
            catch (Exception exp)
            {
                LogRegister("EmailSendInBackground", exp.Message);
            }
        }
Beispiel #4
0
        private string GenerateBody(MailInformation details)
        {
            string body = string.Empty;

            try
            {
                string Emailtemplate = ConfigFields.EmailTemplatePath;

                using (StreamReader reader = new StreamReader(Emailtemplate))
                {
                    body = reader.ReadToEnd();
                }

                // Replace components in HTML
                body = body.Replace("{{ConfigName}}", details.ConfigName);
                body = body.Replace("{{StartedOn}}", details.StartedOn);
                body = body.Replace("{{EndedOn}}", details.EndedOn);
                body = body.Replace("{{RunTime}}", details.RunTime);
                body = body.Replace("{{year}}", DateTime.Now.Year.ToString());
            }
            catch (Exception ex) //Module failed to load
            {
                Logger.Write("error occurred in SendMail() - GenerateBody()" + ex.Message);
            }
            return(body);
        }
        /// <summary>
        /// Sends the mail batch using the SendGrid API
        /// </summary>
        /// <param name="mail">The mail.</param>
        /// <param name="recipients">The recipients.</param>
        /// <param name="onlyTestDontSendMail">if set to <c>true</c> [only test dont send mail].</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public override bool SendMailBatch(MailInformation mail, IEnumerable <JobWorkItem> recipients, bool onlyTestDontSendMail)
        {
            var settings = GetSettings();

            if (recipients == null || recipients.Any() == false)
            {
                throw new ArgumentException("No workitems", "recipients");
            }

            if (recipients.Count() > 1000)
            {
                throw new ArgumentOutOfRangeException("recipients", "SendGrid supports maximum 1000 recipients per batch send.");
            }

            var msg = new SendGridMessage();

            msg.From    = new MailAddress(mail.From);
            msg.Subject = mail.Subject;
            msg.Html    = mail.BodyHtml;
            msg.Text    = mail.BodyText;

            // Add recipinets to header, to hide other recipients in to field.
            List <string> addresses = recipients.Select(r => r.EmailAddress).ToList();

            msg.Header.SetTo(addresses);
            msg.AddSubstitution("%recipient%", addresses);
            // To send message we need to have a to address, set that to from
            msg.To = new MailAddress[] { msg.From };

            if (mail.EnableTracking)
            {
                // true indicates that links in plain text portions of the email
                // should also be overwritten for link tracking purposes.
                msg.EnableClickTracking(true);
                msg.EnableOpenTracking();
            }

            if (mail.CustomProperties.ContainsKey("SendGridCategory"))
            {
                string category = mail.CustomProperties["SendGridCategory"] as string;
                if (string.IsNullOrEmpty(category) == false)
                {
                    msg.SetCategory(category);
                }
            }

            var credentials = new NetworkCredential(settings.Username, settings.Password);

            // Create an Web transport for sending email.
            var transportWeb = new Web(credentials);

            transportWeb.Deliver(msg);

            return(true);
        }
Beispiel #6
0
        public DbResponse SendEmail(MailInformation info)
        {
            MailMessage mail       = new MailMessage();
            SmtpClient  mailer     = new SmtpClient();
            Stream      htmlStream = null;
            var         response   = new DbResponse();

            try
            {
                if (!string.IsNullOrEmpty(info.AttachmentPath))
                {
                    // Add attachment if any
                    AddAttachmentForMail(info, mail);
                }

                // set to mail address
                mail.From = new MailAddress(ConfigFields.MailFromAddress, ConfigFields.MailDisplayName);

                // set recipients for mail
                SetDefaultRecipientsForMail(ref mail);
                SetRecipientsForMail(info, ref mail);

                // set subject
                mail.Subject = ConfigFields.MailSubject;

                mail.IsBodyHtml = true;
                mail.Body       = GenerateBody(info);

                // send mail via SMTP server
                bool isMailSent = SendEmailViaSMTPServer(mail, mailer);

                response = new DbResponse(isMailSent);
            }
            catch (Exception ex) //Module failed to load
            {
                response = new DbResponse(false, ex.Message);
                Logger.Write("error occurred in SendEmail() - EmailUtility; Message: " + ex.Message);
            }

            finally
            {
                if (mail != null)
                {
                    mail.Dispose();
                }
                if (htmlStream != null)
                {
                    htmlStream.Dispose();
                }
            }

            return(response);
        }
        public ActionResult Confirmation(string destination, string subject, string body)
        {
            /// Save some message information to reuse it in a View
            MailInformation information = new MailInformation();
            information.subject = subject;
            information.message = body;

            /// Send email
            EmailSystem.Send(destination, subject, body);

            return View(information);
        }
Beispiel #8
0
 void CreateEmailThread(MailInformation MailInfo)
 {
     try
     {
         ParameterizedThreadStart PTRS = new ParameterizedThreadStart(EmailSendInBackground);
         Thread trMailSender           = new Thread(PTRS);
         trMailSender.Start(MailInfo);
     }
     catch (Exception)
     {
         // iWithdrawals.UpdateForNotifyErrorSent(MailInfo.CustomerID);
     }
 }
Beispiel #9
0
 private void Insert(SendMailModel sendModel, MailInformation Mailinfo, SendMailDO sendmailDO)
 {
     try
     {
         sendModel.CustomerID           = Mailinfo.CustomerID;
         sendModel.EmailText            = Mailinfo.EmailText;
         sendModel.DepositNumber        = Mailinfo.DepositeNumber;
         sendModel.CustomerEmailAddress = Mailinfo.CustomerEmailAddress;
         sendModel.EmailType            = Mailinfo.EmailType;
         sendModel.Subject  = Mailinfo.Subject;
         sendModel.SendDate = FarsiDateServer();
         sendModel.SendTime = ClockServer();
         sendmailDO.Insert(sendModel, true);
     }catch (Exception ex) {}
 }
Beispiel #10
0
        private async Task SendEmailByTemplate(string template, MailInformation mailInformation, CancellationToken cancellationToken)
        {
            var informationWithHtml = mailInformation with
            {
                HtmlBody = await ReadHtmlTemplate(template)
            };

            using var client = new SmtpClient();
            await ConnectAndAuthenticate(client, cancellationToken);

            var message = CreateMessage(informationWithHtml);

            await SendMessage(client, message, cancellationToken);

            await client.DisconnectAsync(true, cancellationToken);
        }
Beispiel #11
0
        private MimeMessage CreateMessage(MailInformation mailInformation)
        {
            var bodyBuilder = new BodyBuilder
            {
                HtmlBody = ReplacePlaceholders(mailInformation.HtmlBody, mailInformation.Placeholders)
            };

            var message = new MimeMessage
            {
                Subject = mailInformation.Subject,
                Body    = bodyBuilder.ToMessageBody()
            };

            message.From.Add(new MailboxAddress("ИП Павлов | Сайт", _configuration.Login));
            message.To.Add(new MailboxAddress(mailInformation.Name, _configuration.Login));

            return(message);
        }
Beispiel #12
0
        public async Task SendCooperationRequest(string name, string company, string email, CancellationToken cancellationToken)
        {
            var placeholders = new Dictionary <string, string>
            {
                { "USERNAME", name },
                { "COMPANY", company },
                { "EMAIL", email }
            };

            var mailInformation = new MailInformation
            {
                Name         = name,
                Email        = email,
                Subject      = QuestionSubject,
                Placeholders = placeholders
            };

            await SendEmailByTemplate(CooperationRequestTemplate, mailInformation, cancellationToken);
        }
Beispiel #13
0
        /// <inheritdoc/>
        public async Task SendQuestionAsync(string name, string email, string question, CancellationToken cancellationToken)
        {
            var placeholders = new Dictionary <string, string>
            {
                { "USERNAME", name },
                { "TEXT", question },
                { "EMAIL", email }
            };

            var mailInformation = new MailInformation
            {
                Name         = name,
                Email        = email,
                Subject      = QuestionSubject,
                Placeholders = placeholders
            };

            await SendEmailByTemplate(QuestionTemplate, mailInformation, cancellationToken);
        }
Beispiel #14
0
        /// <summary>
        /// Sends the newsletter.
        /// </summary>
        /// <returns></returns>
        private string SendNewsletter(Job job)
        {
            JobWorkItems workItemsForProcessing = job.GetWorkItems();

            if (workItemsForProcessing.Items.Count == 0)
            {
                DebugWrite("Work Items collection is empty. Nothing to send.");
                return("Work Items collection is empty. Nothing to send.");
            }

            // Get information about what we're about to send
            EPiMailEngine   mailEngine = new EPiMailEngine();
            MailSenderBase  msbase     = mailEngine.GetMailSender();
            MailInformation mailInfo   = msbase.GetMailMetaData(new PageReference(job.PageId));

            // const int sleepTestInterval = 0;
            DebugWrite(string.Format("Start sending newsletter. Job name: '{0}', Subject: '{1}', From: '{2}'",
                                     job.Name, mailInfo.Subject, mailInfo.From));

            // Send the message

            // For testing, it can be nice to control the time it takes to send
            // each batch
//#if DEBUG
//            if (sleepTestInterval > 0)
//                System.Threading.Thread.Sleep(sleepTestInterval);
//#endif
            // Send with status

            SendMailLog log;

            log = mailEngine.SendNewsletter(mailInfo.Subject,
                                            mailInfo.From,          /* Who we send from */
                                            mailInfo.PageLink,      /* The page to send */
                                            workItemsForProcessing, /* Who we send to */
                                            false /* Not Test Mode */);
//#if DEBUG
//            if (sleepTestInterval > 0)
//                System.Threading.Thread.Sleep(sleepTestInterval);
//#endif
            return(log.GetClearTextLogString(true /* Use br instead of \n */));
        }
Beispiel #15
0
        private void SetRecipientsForMail(MailInformation info, ref MailMessage mail)
        {
            try
            {
                string[] ToId = info.MailToAddress.Trim().Split(';');
                foreach (string ToEmail in ToId)
                {
                    if (ToEmail.Length > 3)
                    {
                        mail.To.Add(new MailAddress(ToEmail));
                    }
                }

                string[] CCId = info.MailCCAddress.Trim().Split(';');
                foreach (string ToEmail in CCId)
                {
                    if (ToEmail.Length > 3)
                    {
                        mail.CC.Add(new MailAddress(ToEmail));
                    }
                }

                string[] BCCId = info.MailBCCAddress.Trim().Split(';');
                foreach (string ToEmail in BCCId)
                {
                    if (ToEmail.Length > 3)
                    {
                        mail.Bcc.Add(new MailAddress(ToEmail));
                    }
                }
            }
            catch (Exception ex) //Module failed to load
            {
                Logger.Write("error occurred in SetRecipientsForMail() - " + ex.Message);
            }
            finally
            {
            }
        }
Beispiel #16
0
    private void UpdateOrAddMail(MailInfo mailInfo)
    {
        bool flag = false;

        for (int i = 0; i < this.MailInformations.get_Count(); i++)
        {
            if (this.MailInformations.get_Item(i).mailInfo.id == mailInfo.id)
            {
                flag = true;
                this.MailInformations.get_Item(i).mailInfo = mailInfo;
                this.MailInformations.get_Item(i).ResetTimeCountDown(mailInfo.timeoutSec);
                break;
            }
        }
        if (!flag)
        {
            MailInformation mailInformation = new MailInformation();
            mailInformation.mailInfo = mailInfo;
            mailInformation.ResetTimeCountDown(mailInfo.timeoutSec);
            this.MailInformations.Add(mailInformation);
        }
    }
    private static int MailSortCompare(MailInformation AF1, MailInformation AF2)
    {
        int result = 0;

        if (AF1.mailInfo.status == 1 && AF2.mailInfo.status == 0)
        {
            result = 1;
        }
        else if (AF1.mailInfo.status == 0 && AF2.mailInfo.status == 1)
        {
            result = -1;
        }
        else if ((AF1.mailInfo.content.items.get_Count() == 0 || AF1.mailInfo.drawMark == 0) && AF2.mailInfo.content.items.get_Count() > 0 && AF2.mailInfo.drawMark != 0)
        {
            result = 1;
        }
        else if (AF1.mailInfo.content.items.get_Count() > 0 && AF1.mailInfo.drawMark != 0 && (AF2.mailInfo.content.items.get_Count() == 0 || AF2.mailInfo.drawMark == 0))
        {
            result = -1;
        }
        else if (AF1.mailInfo.buildDate > AF2.mailInfo.buildDate)
        {
            result = -1;
        }
        else if (AF1.mailInfo.buildDate < AF2.mailInfo.buildDate)
        {
            result = 1;
        }
        else if (AF1.mailInfo.id > AF2.mailInfo.id)
        {
            result = -1;
        }
        else if (AF1.mailInfo.id < AF2.mailInfo.id)
        {
            result = 1;
        }
        return(result);
    }
Beispiel #18
0
        private void AddAttachmentForMail(MailInformation info, MailMessage mail)
        {
            try
            {
                // Specify the file to be attached and sent.
                string file = info.AttachmentPath;

                // Create  the file attachment for this e-mail message.
                Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
                // Add time stamp information for the file.
                ContentDisposition disposition = data.ContentDisposition;
                disposition.CreationDate     = System.IO.File.GetCreationTime(file);
                disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
                disposition.ReadDate         = System.IO.File.GetLastAccessTime(file);
                // Add the file attachment to this e-mail message.
                mail.Attachments.Add(data);
            }

            catch (Exception ex) //Module failed to load
            {
                Logger.Write($"error occurred in SendMail() - AddAttachmentForMail(). Message: {ex.Message}");
            }
        }
Beispiel #19
0
 public MailInformation Get()
 {
     return(MailInformation.GetObjects().FirstOrDefault());
 }
Beispiel #20
0
        void EmailReciveChecker(object State)
        {
            try
            {
                Console.WriteLine("emailCheckOn : " + EmailBankCore.ClockServer());
                TestForm.messageBody[] eBankMessage = new TestForm.messageBody[TestForm.messageBodyList.Count];
                TestForm.messageBodyList.CopyTo(eBankMessage);
                if (!TestForm.EmailReciveCheckerISbusy && !TestForm.EmailAddCheckerISbusy)
                {
                    TestForm.EmailReciveCheckerISbusy = true;
                    foreach (TestForm.messageBody MessageRecived in eBankMessage)
                    {
                        Console.WriteLine("New Message Recived From : " + MessageRecived.MailSender);
                        EmailsenderClass mail = new EmailsenderClass();
                        mail.UserName = "******"[email protected]\"<" + ConfigurationManager.AppSettings["EmailAddress"].ToString() + ">";
                        mail.Password = ConfigurationManager.AppSettings["EmailPassword"].ToString();
                        //______________________________________________________________________________
                        long CustomerID = CustomerIDMining(MessageRecived.DepositeNubmer);
                        if (CustomerID == 0)
                        {
                            PageCreator     PC       = new PageCreator(); //"*****@*****.**"
                            string          Page     = PC.PageBuilder();
                            MailInformation Mailinfo = new MailInformation
                            {
                                CustomerEmailAddress = MessageRecived.MailSender,
                                CustomerID           = CustomerID,
                                EmailText            = Page,
                                MailProperties       = mail,
                                Subject        = "Error",
                                EmailType      = "2",
                                DepositeNumber = MessageRecived.DepositeNubmer
                            };
                            CreateEmailThread(Mailinfo);
                        }
                        else
                        {
                            SBS.DataModel.CustomerModel CustomerInfo;
                            int ii = 0;
                            while (true)
                            {
                                try
                                {
                                    CustomerInfo = iCustomer.SelectOneWithOutDeepLoad(CustomerID);
                                    break;
                                }
                                catch (Exception ex)
                                {
                                    ii++;
                                    if (ii > 10)
                                    {
                                        return;
                                    }
                                    if (Login(UserName, PassWord))
                                    {
                                        iCustomer    = SBS.CommonUtils.FacadeFactory.CustomerManager("", LoggedInUserInfo.UserIdentity.ToString(), (short)SBS.CommonUtils.ConstantData.AppUC.Email_SubSystem, LoggedInUserInfo.TicketStr);
                                        iWithdrawals = SBS.CommonUtils.FacadeFactory.WithdrawalsSettlementManager("", LoggedInUserInfo.UserIdentity.ToString(), (short)SBS.CommonUtils.ConstantData.AppUC.Email_SubSystem, LoggedInUserInfo.TicketStr);
                                    }
                                }
                            }
                            //CustomerInfo.Email = "*****@*****.**";
                            //CustomerInfo.Email = "*****@*****.**";
                            //CustomerInfo.Email = "*****@*****.**";
                            //______________________________________________________________________________
                            if (!string.IsNullOrEmpty(CustomerInfo.Email))
                            {
                                PageCreator     PC      = new PageCreator(); //"*****@*****.**"
                                UserInformation UserInf = new UserInformation
                                {
                                    PreName       = "",
                                    Name          = CustomerInfo.DisplayName,
                                    ActionType    = "گردش سپرده",
                                    DepositNubmer = MessageRecived.DepositeNubmer,
                                    Amount        = CustomerInfo.Amount.ToString(),
                                    Comment       = CustomerInfo.Comment,
                                    Date          = FarsiDateServer(),
                                    RemainAmount  = CustomerInfo.RemainAmount.ToString(),
                                    Time          = ClockServer(),
                                    IsTransaction = false,
                                };
                                if (MessageRecived.TransactionCountRequested <= 200)
                                {
                                    UserInf.TransactionCountRequested = MessageRecived.TransactionCountRequested;
                                }
                                else
                                {
                                    UserInf.TransactionCountRequested = 200;
                                }
                                if (MessageRecived.Blocked)
                                {
                                    string          Page     = PC.PageBuilder(UserInf);
                                    MailInformation Mailinfo = new MailInformation
                                    {
                                        CustomerEmailAddress = CustomerInfo.Email,
                                        CustomerID           = CustomerID,
                                        EmailText            = Page,
                                        MailProperties       = mail,
                                        Subject        = "بیش از حد مجاز",
                                        EmailType      = "2",
                                        DepositeNumber = MessageRecived.DepositeNubmer
                                    };
                                    CreateEmailThread(Mailinfo);
                                }
                                else
                                {
                                    List <ReportDetails> LRep = ReportDetailsBuilder(MessageRecived.DepositeNubmer, MessageRecived.TransactionCountRequested);
                                    UserInf.RealTransactionCount = short.Parse(LRep.Count.ToString());
                                    string          Page     = PC.PageBuilder(UserInf, LRep);
                                    MailInformation Mailinfo = new MailInformation
                                    {
                                        CustomerEmailAddress = CustomerInfo.Email,
                                        CustomerID           = CustomerID,
                                        EmailText            = Page,
                                        MailProperties       = mail,
                                        Subject        = "گردش سپرده",
                                        EmailType      = "2",
                                        DepositeNumber = MessageRecived.DepositeNubmer
                                    };
                                    CreateEmailThread(Mailinfo);
                                }
                            }
                        }
                        while (true)
                        {
                            if (!TestForm.EmailAddCheckerISbusy)
                            {
                                TestForm.EmailAddCheckerISbusy = true;
                                TestForm.messageBodyList.Remove(MessageRecived);
                                TestForm.EmailAddCheckerISbusy = false;
                                break;
                            }
                        }
                    }
                    TestForm.EmailReciveCheckerISbusy = false;
                }
            }

            catch (Exception ex)
            {
                LogRegister("EmailReciveChecker", ex.Message);
            }
        }
Beispiel #21
0
        public void EmailBiulder()
        {
            long CustomerID = 0;

            try
            {
                string           text = "";
                EmailsenderClass mail = new EmailsenderClass();
                mail.UserName = "******"[email protected]\"<" + ConfigurationManager.AppSettings["EmailAddress"].ToString() + ">";
                mail.Password = ConfigurationManager.AppSettings["EmailPassword"].ToString();
                List <SBS.DataModel.CustomerModel> SDCustomermodel = new List <CustomerModel>();
                // setLastID(0);
                try
                {
                    SDCustomermodel = iWithdrawals.SelectForNotifyEmail(getLastID(), getDate());
                }
                catch (Exception)
                {
                    Thread.Sleep(10000);
                    EmailBankCoreMethod(UserName, PassWord);
                    EmailBiulder();
                    return;
                }
                foreach (SBS.DataModel.CustomerModel CustomerModelRow in SDCustomermodel)
                {
                    UserInformation UserInf;
                    try
                    {
                        CustomerID = CustomerModelRow.ID.Value;
                        UserInf    = new UserInformation
                        {
                            PreName       = "",
                            Name          = CustomerModelRow.DisplayName,
                            ActionType    = CustomerModelRow.Moaref + " سپرده ",
                            DepositNubmer = CustomerModelRow.DepositName,
                            Amount        = CustomerModelRow.Amount.ToString(),
                            Comment       = CustomerModelRow.Comment,
                            Date          = CustomerModelRow.Date,
                            RemainAmount  = CustomerModelRow.RemainAmount.ToString(),
                            Time          = CustomerModelRow.Clock, IsTransaction = true
                        };
                        UserInf.PreName = "";
                        PageCreator Page = new PageCreator();
                        text = Page.PageBuilder(UserInf, ReportDetailsBuilder(UserInf.DepositNubmer, 5));
                    }
                    catch (Exception ex)
                    {
                        UserInf = new UserInformation();
                        //iWithdrawals.UpdateForNotifyErrorSent(CustomerID);
                    }
                    MailInformation Mailinfo = new MailInformation {
                        CustomerEmailAddress = CustomerModelRow.Email, CustomerID = CustomerID, EmailText = text, MailProperties = mail, Subject = UserInf.ActionType, EmailType = "1", DepositeNumber = UserInf.DepositNubmer
                    };
                    if (CustomerID != 0)
                    {
                        setLastID(CustomerID);
                    }
                    CreateEmailThread(Mailinfo);
                }

                CurrentlyInUse = false;
            }
            catch (Exception ex)
            {
                CurrentlyInUse = false;
                LogRegister("EmailBiulder", ex.Message);
            }
        }
Beispiel #22
0
        /// <summary>
        /// Sends the mail batch using the SendGrid API
        /// </summary>
        /// <param name="mail">The mail.</param>
        /// <param name="recipients">The recipients.</param>
        /// <param name="onlyTestDontSendMail">if set to <c>true</c> [only test dont send mail].</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public override bool SendMailBatch(MailInformation mail, IEnumerable <JobWorkItem> recipients, bool onlyTestDontSendMail)
        {
            var settings = GetSettings();

            if (recipients == null || recipients.Any() == false)
            {
                throw new ArgumentException("No workitems", nameof(recipients));
            }

            if (recipients.Count() > 1000)
            {
                throw new ArgumentOutOfRangeException(nameof(recipients), "SendGrid supports maximum 1000 recipients per batch send.");
            }

            var msg = new SendGridMessage
            {
                From             = new EmailAddress(mail.From),
                Subject          = mail.Subject,
                HtmlContent      = mail.BodyHtml,
                PlainTextContent = mail.BodyText
            };

            var personalizations = new List <Personalization>();

            foreach (var jobWorkItem in recipients)
            {
                var personalization = new Personalization();
                personalization.Tos = new List <EmailAddress>
                {
                    new EmailAddress(jobWorkItem.EmailAddress)
                };
                personalization.Substitutions = new Dictionary <string, string>
                {
                    { "%recipient%", jobWorkItem.EmailAddress }
                };

                personalizations.Add(personalization);
            }

            msg.Personalizations = personalizations;

            if (mail.EnableTracking)
            {
                // true indicates that links in plain text portions of the email
                // should also be overwritten for link tracking purposes.
                msg.SetClickTracking(true, true);
                msg.SetOpenTracking(true);
            }

            if (mail.CustomProperties.ContainsKey("SendGridCategory"))
            {
                string category = mail.CustomProperties["SendGridCategory"] as string;
                if (string.IsNullOrEmpty(category) == false)
                {
                    msg.Categories.Add(category);
                }
            }

            var client = new SendGridClient(settings.ApiKey);

            client.SendEmailAsync(msg).Wait();

            return(true);
        }