Exemplo n.º 1
0
        public async Task <bool> Handle(SaveEmailCommand request, CancellationToken cancellationToken)
        {
            if (!request.IsValid())
            {
                NotifyValidationErrors(request);
                return(false);
            }

            var email = await _emailRepository.GetByType(request.Type);

            if (email == null)
            {
                email = request.ToModel();
                _emailRepository.Add(email);
            }
            else
            {
                email.Update(request);
                _emailRepository.Update(email);
            }


            if (await Commit())
            {
                await Bus.RaiseEvent(new EmailSavedEvent(email));

                return(true);
            }

            return(false);
        }
Exemplo n.º 2
0
        private async Task EnqueueEmail(EmailTemplateId id, string recipient, IReadOnlyDictionary <string, string> fields, params IEntity[] entities)
        {
            var template = await emailRepository.GetEmailTemplateAsync(id);

            Email email = template.CreateEmail(recipient, fields, entities);

            emailRepository.Add(email);
            await UnitOfWork.SaveAsync();
        }
Exemplo n.º 3
0
 /// <summary>
 /// Send multiple emails
 /// </summary>
 /// <param name="emails"></param>
 public void SendMail(List <Email> emails)
 {
     // Add all the emails to the email table
     // They are sent every X seconds by the email sending task
     foreach (var email in emails)
     {
         _emailRepository.Add(email);
     }
 }
Exemplo n.º 4
0
        /// <summary>
        /// Send multiple emails
        /// </summary>
        /// <param name="emails"></param>
        public void SendMail(List <Email> emails)
        {
            var settings = _settingsService.GetSettings();

            // Add all the emails to the email table
            // They are sent every X seconds by the email sending task
            foreach (var email in emails)
            {
                // Sort local images in emails
                email.Body = StringUtils.AppendDomainToImageUrlInHtml(email.Body, settings.ForumUrl.TrimEnd('/'));
                _emailRepository.Add(email);
            }
        }
Exemplo n.º 5
0
 public async Task <IActionResult> PostEmail([FromBody] Email email)
 {
     if (!ModelState.isValid)
     {
         return(BadRequest(ModelState));
     }
     try {
         _repo.Add(email);
         return(Ok(email));
     } catch (DbUpdateConcurrencyException) {
         throw;
     }
 }
Exemplo n.º 6
0
        public bool Invoke(EmailMessageModel email)
        {
            if (!email.IsValid())
            {
                return(false);
            }

            var dbMessage = AutoMapper.Mapper.Map <EmailMessage>(email);

            emailRepository.Add(dbMessage);
            _unitOfWork.Save();

            return(true);
        }
        public JsonResult SaveEmailKM(string Emails)
        {
            Email mail = new Email()
            {
                Emails = Emails,
                SDate  = DateTime.Now
            };

            _emailRepository.Add(mail);
            _unitOfWork.Commit();
            return(Json(new
            {
                message = "Bạn đã đăng ký thành công!"
            }, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 8
0
        public GeneralResponse AddEmail(AddEmailRequest request)
        {
            GeneralResponse response = new GeneralResponse();

            try
            {
                Email email = new Email();
                email.ID             = Guid.NewGuid();
                email.CreateDate     = PersianDateTime.Now;
                email.CreateEmployee = _employeeRepository.FindBy(request.CreateEmployeeID);
                email.Body           = request.Body;
                email.Customer       = this._customerRepository.FindBy(request.CustomerID);
                email.Subject        = request.Subject;

                email.RowVersion = 1;

                #region Validation

                if (email.GetBrokenRules().Count() > 0)
                {
                    foreach (BusinessRule businessRule in email.GetBrokenRules())
                    {
                        response.ErrorMessages.Add(businessRule.Rule);
                    }

                    return(response);
                }

                #endregion

                _emailRepository.Add(email);
                _uow.Commit();
            }
            catch (Exception ex)
            {
                response.ErrorMessages.Add(ex.Message);
            }

            return(response);
        }
Exemplo n.º 9
0
        public IActionResult AddEmail(EmailModel e_mail_address)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    if (e_mail_address != null)
                    {
                        _email_repo.Add(e_mail_address);
                        return(RedirectToActionPermanent("Index", "Home"));
                    }
                    else
                    {
                        return(RedirectToAction("EmailExists"));
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }

            return(View());
        }
Exemplo n.º 10
0
        public Task SendEmailAsync(EmailMessage emailMessage, string accountName = null, string id = null, string direction = null)
        {
            Email emailObject = new Email();
            Guid? emailId     = Guid.NewGuid();

            if (!string.IsNullOrEmpty(id))
            {
                emailId     = Guid.Parse(id);
                emailObject = _emailRepository.Find(null, q => q.Id == emailId)?.Items?.FirstOrDefault();
                if (emailObject == null)
                {
                    emailObject = new Email()
                    {
                        Id     = emailId,
                        Status = StatusType.Unknown.ToString()
                    };
                }
            }

            Email email = new Email();

            if (!string.IsNullOrEmpty(id))
            {
                email.Id = emailId;
            }

            //find email settings and determine is email is enabled/disabled
            var organizationId = Guid.Parse(_organizationManager.GetDefaultOrganization().Id.ToString());
            var emailSettings  = _emailSettingsRepository.Find(null, s => s.OrganizationId == organizationId).Items.FirstOrDefault();
            //check if accountName exists
            var existingAccount = _emailAccountRepository.Find(null, d => d.Name.ToLower(null) == accountName?.ToLower(null))?.Items?.FirstOrDefault();

            if (existingAccount == null)
            {
                existingAccount = _emailAccountRepository.Find(null, d => d.IsDefault && !d.IsDisabled).Items.FirstOrDefault();
            }

            //if there are no records in the email settings table for that organization, email should be disabled
            if (emailSettings == null)
            {
                email.Status = StatusType.Blocked.ToString();
                email.Reason = "Email disabled.  Please configure email settings.";
            }
            //if there are email settings but they are disabled, don't send email
            else if (emailSettings != null && emailSettings.IsEmailDisabled)
            {
                email.Status = StatusType.Blocked.ToString();
                email.Reason = "Email functionality has been disabled.";
            }
            else
            {
                if (existingAccount == null && emailSettings != null)
                {
                    existingAccount = _emailAccountRepository.Find(null, a => a.IsDefault == true && a.IsDisabled == false)?.Items?.FirstOrDefault();
                    if (existingAccount == null)
                    {
                        email.Status = StatusType.Failed.ToString();
                        email.Reason = $"Account '{accountName}' could be found.";
                    }
                    if (existingAccount != null && existingAccount.IsDisabled == true)
                    {
                        email.Status = StatusType.Blocked.ToString();
                        email.Reason = $"Account '{accountName}' has been disabled.";
                    }
                }
                //set from email address
                else if (existingAccount != null)
                {
                    EmailAddress        fromEmailAddress = new EmailAddress(existingAccount.FromName, existingAccount.FromEmailAddress);
                    List <EmailAddress> emailAddresses   = new List <EmailAddress>();

                    foreach (EmailAddress emailAddress in emailMessage.From)
                    {
                        if (!string.IsNullOrEmpty(emailAddress.Address))
                        {
                            emailAddresses.Add(emailAddress);
                        }
                    }
                    emailMessage.From.Clear();
                    foreach (EmailAddress emailAddress in emailAddresses)
                    {
                        emailMessage.From.Add(emailAddress);
                    }
                    emailMessage.From.Add(fromEmailAddress);
                }

                //remove email addresses in to, cc, and bcc lists with domains that are blocked or not allowed
                List <EmailAddress> toList  = new List <EmailAddress>();
                List <EmailAddress> ccList  = new List <EmailAddress>();
                List <EmailAddress> bccList = new List <EmailAddress>();

                if (string.IsNullOrEmpty(emailSettings.AllowedDomains))
                {
                    if (!string.IsNullOrEmpty(emailSettings.BlockedDomains))
                    {
                        //remove any email address that is in blocked domain
                        IEnumerable <string>?denyList = (new List <string>(emailSettings?.BlockedDomains?.Split(','))).Select(s => s.ToLowerInvariant().Trim());
                        foreach (EmailAddress address in emailMessage.To)
                        {
                            if (!string.IsNullOrEmpty(address.Address))
                            {
                                MailboxAddress mailAddress = new MailboxAddress(address.Address);
                                if (!denyList.Contains(mailAddress.Address.Split("@")[1].ToLowerInvariant()))
                                {
                                    toList.Add(address);
                                }
                            }
                        }
                        emailMessage.To.Clear();
                        emailMessage.To = toList;

                        foreach (EmailAddress address in emailMessage.CC)
                        {
                            if (!string.IsNullOrEmpty(address.Address))
                            {
                                MailboxAddress mailAddress = new MailboxAddress(address.Address);
                                if (!denyList.Contains(mailAddress.Address.Split("@")[1].ToLowerInvariant()))
                                {
                                    ccList.Add(address);
                                }
                            }
                        }
                        emailMessage.CC.Clear();
                        emailMessage.CC = ccList;

                        foreach (EmailAddress address in emailMessage.Bcc)
                        {
                            if (!string.IsNullOrEmpty(address.Address))
                            {
                                MailboxAddress mailAddress = new MailboxAddress(address.Address);
                                if (!denyList.Contains(mailAddress.Address.Split("@")[1].ToLowerInvariant()))
                                {
                                    bccList.Add(address);
                                }
                            }
                        }
                        emailMessage.Bcc.Clear();
                        emailMessage.Bcc = bccList;
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(emailSettings.AllowedDomains))
                    {
                        //remove any email address that is not on white list
                        IEnumerable <string> allowList = (new List <string>(emailSettings.AllowedDomains.Split(','))).Select(s => s.ToLowerInvariant().Trim());
                        foreach (EmailAddress address in emailMessage.To)
                        {
                            if (!string.IsNullOrEmpty(address.Address))
                            {
                                MailboxAddress mailAddress = new MailboxAddress(address.Address);
                                if (allowList.Contains(mailAddress.Address.Split("@")[1].ToLowerInvariant()))
                                {
                                    toList.Add(address);
                                }
                            }
                        }
                        emailMessage.To.Clear();
                        emailMessage.To = toList;

                        foreach (EmailAddress address in emailMessage.CC)
                        {
                            if (!string.IsNullOrEmpty(address.Address))
                            {
                                MailboxAddress mailAddress = new MailboxAddress(address.Address);
                                if (allowList.Contains(mailAddress.Address.Split("@")[1].ToLowerInvariant()))
                                {
                                    ccList.Add(address);
                                }
                            }
                        }
                        emailMessage.CC.Clear();
                        emailMessage.CC = ccList;

                        foreach (EmailAddress address in emailMessage.Bcc)
                        {
                            if (!string.IsNullOrEmpty(address.Address))
                            {
                                MailboxAddress mailAddress = new MailboxAddress(address.Address);
                                if (allowList.Contains(mailAddress.Address.Split("@")[1].ToLowerInvariant()))
                                {
                                    bccList.Add(address);
                                }
                            }
                        }
                        emailMessage.Bcc.Clear();
                        emailMessage.Bcc = bccList;
                    }
                }

                if (emailMessage.To.Count == 0)
                {
                    email.Status = StatusType.Blocked.ToString();
                    email.Reason = "No email addresses to send email to.";
                }

                //add any necessary additional email addresses (administrators, etc.)
                if (!string.IsNullOrEmpty(emailSettings.AddToAddress))
                {
                    foreach (string toAddress in emailSettings.AddToAddress.Split(','))
                    {
                        EmailAddress emailAddress = new EmailAddress(toAddress, toAddress);
                        emailMessage.To.Add(emailAddress);
                    }
                }
                if (!string.IsNullOrEmpty(emailSettings.AddCCAddress))
                {
                    foreach (string CCAddress in emailSettings.AddCCAddress.Split(','))
                    {
                        EmailAddress emailAddress = new EmailAddress(CCAddress, CCAddress);
                        emailMessage.CC.Add(emailAddress);
                    }
                }
                if (!string.IsNullOrEmpty(emailSettings.AddBCCAddress))
                {
                    foreach (string BCCAddress in emailSettings.AddBCCAddress.Split(','))
                    {
                        EmailAddress emailAddress = new EmailAddress(BCCAddress);
                        emailMessage.Bcc.Add(emailAddress);
                    }
                }

                //add subject and body prefixes/suffixes
                if (!string.IsNullOrEmpty(emailSettings.SubjectAddPrefix) && !string.IsNullOrEmpty(emailSettings.SubjectAddSuffix))
                {
                    emailMessage.Subject = string.Concat(emailSettings.SubjectAddPrefix, emailMessage.Subject, emailSettings.SubjectAddSuffix);
                }
                if (!string.IsNullOrEmpty(emailSettings.SubjectAddPrefix) && string.IsNullOrEmpty(emailSettings.SubjectAddSuffix))
                {
                    emailMessage.Subject = string.Concat(emailSettings.SubjectAddPrefix, emailMessage.Subject);
                }
                if (string.IsNullOrEmpty(emailSettings.SubjectAddPrefix) && !string.IsNullOrEmpty(emailSettings.SubjectAddSuffix))
                {
                    emailMessage.Subject = string.Concat(emailMessage.Subject, emailSettings.SubjectAddSuffix);
                }
                else
                {
                    emailMessage.Subject = emailMessage.Subject;
                }

                //check if email message body is html or plaintext
                if (emailMessage.IsBodyHtml)
                {
                    if (!string.IsNullOrEmpty(emailSettings.BodyAddPrefix) && !string.IsNullOrEmpty(emailSettings.BodyAddSuffix))
                    {
                        emailMessage.Body = string.Concat(emailSettings.BodyAddPrefix, emailMessage.Body, emailSettings.BodyAddSuffix);
                    }
                    if (!string.IsNullOrEmpty(emailSettings.BodyAddPrefix) && string.IsNullOrEmpty(emailSettings.BodyAddSuffix))
                    {
                        emailMessage.Body = string.Concat(emailSettings.BodyAddPrefix, emailMessage.Body);
                    }
                    if (string.IsNullOrEmpty(emailSettings.BodyAddPrefix) && !string.IsNullOrEmpty(emailSettings.BodyAddSuffix))
                    {
                        emailMessage.Body = string.Concat(emailMessage.Body, emailSettings.BodyAddSuffix);
                    }
                    else
                    {
                        emailMessage.Body = emailMessage.Body;
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(emailSettings.BodyAddPrefix) && !string.IsNullOrEmpty(emailSettings.BodyAddSuffix))
                    {
                        emailMessage.PlainTextBody = string.Concat(emailSettings.BodyAddPrefix, emailMessage.PlainTextBody, emailSettings.BodyAddSuffix);
                    }
                    if (!string.IsNullOrEmpty(emailSettings.BodyAddPrefix) && string.IsNullOrEmpty(emailSettings.BodyAddSuffix))
                    {
                        emailMessage.PlainTextBody = string.Concat(emailSettings.BodyAddPrefix, emailMessage.PlainTextBody);
                    }
                    if (string.IsNullOrEmpty(emailSettings.BodyAddPrefix) && !string.IsNullOrEmpty(emailSettings.BodyAddSuffix))
                    {
                        emailMessage.PlainTextBody = string.Concat(emailMessage.PlainTextBody, emailSettings.BodyAddSuffix);
                    }
                    else
                    {
                        emailMessage.PlainTextBody = emailMessage.Body;
                    }
                }

                //send email
                ISendEmailChore sendEmailChore = null;

                if (existingAccount != null)
                {
                    if (existingAccount.Provider == "SMTP")
                    {
                        sendEmailChore = new SmtpSendEmailChore(existingAccount, emailSettings);
                    }
                    else if (existingAccount.Provider == "Azure")
                    {
                        sendEmailChore = new AzureSendEmailChore(emailSettings, existingAccount);
                    }
                }

                if (sendEmailChore != null)
                {
                    try
                    {
                        if (email.Status != StatusType.Blocked.ToString() || email.Status != StatusType.Failed.ToString())
                        {
                            sendEmailChore.SendEmail(emailMessage);
                            email.Status = StatusType.Sent.ToString();
                            email.Reason = "Email was sent successfully.";
                        }
                    }
                    catch (Exception ex)
                    {
                        email.Status = StatusType.Failed.ToString();
                        email.Reason = "Error: " + ex.Message;
                    }
                }
                else
                {
                    email.Status = StatusType.Failed.ToString();
                    email.Reason = "Email failed to send.";
                }
            }

            //log email and its status
            if (existingAccount != null)
            {
                email.EmailAccountId = Guid.Parse(existingAccount.Id.ToString());
            }
            email.SentOnUTC = DateTime.UtcNow;
            string newEmailMessage = Regex.Replace(emailMessage.Body, @"(<sensitive(\s|\S)*?<\/sensitive>)", "NULL");

            email.EmailObjectJson = newEmailMessage;
            List <string> nameList  = new List <string>();
            List <string> emailList = new List <string>();

            foreach (EmailAddress address in emailMessage.From)
            {
                nameList.Add(address.Name);
                emailList.Add(address.Address);
            }
            email.SenderName    = JsonConvert.SerializeObject(nameList);
            email.SenderAddress = JsonConvert.SerializeObject(emailList);
            email.SenderUserId  = _applicationUser?.PersonId;
            if (string.IsNullOrEmpty(direction))
            {
                email.Direction = Direction.Unknown.ToString();
            }
            else
            {
                email.Direction = direction;
            }

            //TODO: add logic to next two lines of code to allow for assignment of these Guids
            email.ConversationId = null;
            email.ReplyToEmailId = null;

            if (emailObject.Status == StatusType.Unknown.ToString())
            {
                email.Id        = emailObject.Id;
                email.CreatedOn = DateTime.UtcNow;
                email.CreatedBy = _httpContextAccessor.HttpContext.User.Identity.Name;
                _emailRepository.Add(email);
            }
            else if (email.Id != null && email.Id != emailId)
            {
                email.CreatedOn = DateTime.UtcNow;
                email.CreatedBy = _httpContextAccessor.HttpContext.User.Identity.Name;
                _emailRepository.Add(email);
            }
            else
            {
                emailObject.EmailAccountId  = email.EmailAccountId;
                emailObject.SentOnUTC       = email.SentOnUTC;
                emailObject.EmailObjectJson = email.EmailObjectJson;
                emailObject.SenderName      = email.SenderName;
                emailObject.SenderAddress   = email.SenderAddress;
                emailObject.SenderUserId    = email.SenderUserId;
                emailObject.Direction       = email.Direction;
                emailObject.ConversationId  = email.ConversationId;
                emailObject.ReplyToEmailId  = email.ReplyToEmailId;
                emailObject.Status          = email.Status;
                emailObject.Reason          = email.Reason;
                _emailRepository.Update(emailObject);
            }
            return(Task.CompletedTask);
        }
Exemplo n.º 11
0
 private void Enqueue(Email email)
 {
     access.CheckWritable();
     emails.Add(email);
 }
Exemplo n.º 12
0
 public void Add(Email item)
 {
     _emailRepository.Add(item);
 }
Exemplo n.º 13
0
        public GeneralResponse PrepareToAddCustomerLevel(AddCustomerLevelRequest request)
        {
            GeneralResponse response = new GeneralResponse();

            try
            {
                CustomerLevel customerLevel = new CustomerLevel();
                customerLevel.ID             = Guid.NewGuid();
                customerLevel.CreateDate     = PersianDateTime.Now;
                customerLevel.CreateEmployee = _employeeRepository.FindBy(request.CreateEmployeeID);
                customerLevel.Customer       = this._customerRepository.FindBy(request.CustomerID);
                customerLevel.Level          = this._levelRepository.FindBy(request.NewLevelID);
                customerLevel.Note           = request.Note;


                customerLevel.RowVersion = 1;

                #region Validation

                if (customerLevel.GetBrokenRules().Count() > 0)
                {
                    foreach (BusinessRule businessRule in customerLevel.GetBrokenRules())
                    {
                        response.ErrorMessages.Add(businessRule.Rule);
                    }

                    return(response);
                }

                #endregion

                #region Check Conditions

                if (customerLevel.Customer.Center == null)
                {
                    response.ErrorMessages.Add("هیچ گونه مرکز مخابراتی برای مشتری مورد نظر تعریف نشده است. لطفاً با مراجعه به تنظیمات، مرکز مخابراتی مربوط به پیش شماره مشتری را تعریف کنید.");

                    return(response);
                }

                CheckConditionResponse cres = CheckLevelCondition(customerLevel.Level, customerLevel.Customer);
                if (!cres.CanEnter)
                {
                    foreach (string error in cres.ErrorMessages)
                    {
                        response.ErrorMessages.Add(error);
                    }

                    return(response);
                }

                #endregion

                #region Change Customer Query Count

                #endregion

                #region CreateSupport

                if (customerLevel.Level.CreateSupportOnEnter)
                {
                    Support support = new Support();
                    support.ID             = Guid.NewGuid();
                    support.CreateDate     = PersianDateTime.Now;
                    support.CreateEmployee = customerLevel.CreateEmployee;
                    support.SupportTitle   = "پشتیبانی ";
                    support.SupportComment = "پشتیبانی ایجاد شده خودکار توسط سیستم";
                    support.Customer       = customerLevel.Customer;
                    support.CreateBy       = Support.Creator.BySystem;
                    support.SupportStatus  =
                        _supportStatusRepository.FindAll().Where(x => x.Key == "NoStatus").FirstOrDefault();
                    _supportRepository.Add(support);
                }

                #endregion

                _customerLevelRepository.Add(customerLevel);

                #region Query Customer Count

                //اگر مشتری جدید بود فقط به مرحله جدید یک واحد اضافه کن
                if (request.NewCustomer == true)
                {
                    Infrastructure.Querying.Query newQuery = new Infrastructure.Querying.Query();
                    Criterion crt1 = new Criterion("Level.ID", request.NewLevelID, CriteriaOperator.Equal);
                    newQuery.Add(crt1);
                    Model.Customers.Query OldQuery = _queryRepository.FindBy(newQuery).FirstOrDefault();
                    if (OldQuery != null)
                    {
                        OldQuery.CustomerCount += 1;
                        _queryRepository.Save(OldQuery);
                    }
                }
                // اگر مشتری قبلی بود از مرحله قبل یکی کم و به مرحله جدید یکی اضافه کنذ
                else
                {
                    Infrastructure.Querying.Query oldQuery = new Infrastructure.Querying.Query();
                    Criterion crt1 = new Criterion("Level.ID", customerLevel.Customer.Level.ID, CriteriaOperator.Equal);
                    oldQuery.Add(crt1);
                    Model.Customers.Query OldQuery = _queryRepository.FindBy(oldQuery).FirstOrDefault();
                    OldQuery.CustomerCount -= 1;
                    _queryRepository.Save(OldQuery);

                    Infrastructure.Querying.Query newQuery = new Infrastructure.Querying.Query();
                    Criterion crt2 = new Criterion("Level.ID", request.NewLevelID, CriteriaOperator.Equal);
                    newQuery.Add(crt2);
                    Model.Customers.Query NewQuery = _queryRepository.FindBy(newQuery).FirstOrDefault();
                    NewQuery.CustomerCount += 1;
                    _queryRepository.Save(NewQuery);
                }

                #endregion

                #region Change Customer Level In Customer Table

                Customer customer = _customerRepository.FindBy(request.CustomerID);
                customer.Level          = _levelRepository.FindBy(request.NewLevelID);
                customer.LevelEntryDate = PersianDateTime.Now;
                _customerRepository.Save(customer);


                #endregion

                _uow.Commit();

                #region Sending Email

                string displayName = "ماهان نت";
                string subject;
                //List<string> recipients = new List<string>();
                GeneralResponse sendResponse = new GeneralResponse();


                // if OnEnterSendEmail is true
                if (customerLevel.Level.OnEnterSendEmail)
                {
                    email.ID             = Guid.NewGuid();
                    email.CreateDate     = PersianDateTime.Now;
                    email.CreateEmployee = customerLevel.CreateEmployee;
                    email.Customer       = customerLevel.Customer;
                    subject          = customer.Name;
                    email.Subject    = subject;
                    email.RowVersion = 1;

                    #region Validation

                    if (email.GetBrokenRules().Count() > 0)
                    {
                        foreach (BusinessRule businessRule in email.GetBrokenRules())
                        {
                            response.ErrorMessages.Add(businessRule.Rule);
                        }

                        return(response);
                    }

                    #endregion

                    #region Send Email

                    // Replacing:
                    string emailBody = ReplaceTemplate(customerLevel.Level.EmailText, customerLevel.Customer.ConvertToCustomerView());

                    email.Body = emailBody;

                    string recipient = email.Customer.Email;
                    if (recipient == null || recipient == string.Empty)
                    {
                        response.ErrorMessages.Add("برای مشتری مورد نظر هیچ ایمیلی در سیستم تعریف نشده است.");

                        return(response);
                    }

                    //===============  Threading:
                    EmailData emailData = new EmailData()
                    {
                        displayName = displayName,
                        body        = emailBody,
                        subject     = subject,
                        recipient   = recipient
                    };

                    Thread oThread = new Thread(SendEmailVoid);
                    oThread.Start(emailData);

                    #endregion

                    _emailRepository.Add(email);
                }

                #endregion

                #region Sending Sms

                if (customerLevel.Level.OnEnterSendSMS)
                {
                    Sms sms = new Sms();
                    sms.ID             = Guid.NewGuid();
                    sms.CreateDate     = PersianDateTime.Now;
                    sms.CreateEmployee = customerLevel.CreateEmployee;
                    //sms.Body = customerLevel.Level.SMSText;
                    sms.Customer   = customerLevel.Customer;
                    sms.RowVersion = 1;

                    #region Validation

                    if (sms.GetBrokenRules().Count() > 0)
                    {
                        foreach (BusinessRule businessRule in sms.GetBrokenRules())
                        {
                            response.ErrorMessages.Add(businessRule.Rule);
                        }

                        return(response);
                    }

                    #endregion

                    string smsBody = ReplaceTemplate(customerLevel.Level.SMSText, customerLevel.Customer.ConvertToCustomerView());

                    // Threading
                    SmsData smsData = new SmsData()
                    {
                        body = smsBody, phoneNumber = customerLevel.Customer.Mobile1
                    };
                    Thread oThread = new Thread(SendSmsVoid);
                    oThread.Start(smsData);

                    _smsRepository.Add(sms);
                }

                #endregion
            }
            catch (Exception ex)
            {
                response.ErrorMessages.Add(ex.Message);
            }

            return(response);
        }