Exemple #1
0
 public async Task <EmailTemplate> GetEmailTemplate(EmailTemplateType type)
 {
     if (type == EmailTemplateType.RejectionEmail)
     {
         return(await _apiClient.RequestEmailSdk.GetTemplate(type));
     }
     else if (type == EmailTemplateType.AuditInspection ||
              type == Model.EmailTemplateType.RescheduleAuditInspection)
     {
         return(await _apiClient.JobOrderEmailSdk.GetTemplate(type));
     }
     else if (type == EmailTemplateType.ShowCause ||
              type == EmailTemplateType.Warning ||
              type == EmailTemplateType.Compound ||
              type == EmailTemplateType.Suspension ||
              type == EmailTemplateType.ImmediateSuspension ||
              type == EmailTemplateType.Revocation)
     {
         return(await _apiClient.CaseEmailSdk.GetTemplate(type));
     }
     else
     {
         return(await _apiClient.IdentityEmailSdk.GetTemplate(type));
     }
 }
Exemple #2
0
        private IFluentEmail CreateEmailMessage(Message message, EmailTemplateType emailTemplateType)
        {
            var attachements = new List <Attachment>();

            if (message.Attachments is not null && message.Attachments.Any())
            {
                byte[] fileBytes;
                foreach (var attachment in message.Attachments)
                {
                    using var ms = new MemoryStream();
                    attachment.CopyTo(ms);
                    fileBytes = ms.ToArray();
                    attachements.Add(new Attachment {
                        Filename = attachment.FileName, Data = ms, ContentType = attachment.ContentType
                    });
                }
            }
            var createdEmail = _emailClientFactory
                               .Create()
                               .To(string.Join(";", message.To))
                               .Subject(message.Subject)
                               .Attach(attachements);


            if (!message.IsRazorTemplate)
            {
                return(createdEmail.Body(message.Content));
            }

            var path = GetTemplatePath(emailTemplateType, _authTemplatePath);

            return(createdEmail.UsingTemplateFromFile(path, message.Model));
        }
        public bool SendMessage(EmailTemplateType type, Client client, LoanRequest loanRequest, string text = null)
        {
            var template = this.emailTemplatesService.GetByType(type);
            var body     = template.Text;
            var subject  = template.Subject;

            if (!string.IsNullOrEmpty(text))
            {
                body = body.Replace("{text}", text);
            }
            subject = subject.Replace("{firstname}", client.FirstName);
            body    = this.MassReplace(
                body,
                new Collection <KeyValuePair <string, string> > {
                new KeyValuePair <string, string>("{firstname}", client.FirstName),
                new KeyValuePair <string, string>("{lastname}", client.LastName),
                new KeyValuePair <string, string>("{time}", DateTime.Now.ToShortTimeString()),
                new KeyValuePair <string, string>("{date}", DateTime.Now.ToShortDateString()),
                new KeyValuePair <string, string>("{currentamount}", client.PrimaryAccount.Amount.ToString("C0"))
            });
            body    = body.Replace("{amount}", loanRequest.Amount.ToString());
            body    = body.Replace("{productname}", loanRequest.LoanProduct.Name);
            subject = subject.Replace("{lastname}", client.FirstName);
            return(this.SendMessage(subject, body, client.Email));
        }
        /// <summary>
        /// If we add a template we add a type for it other wise we don't edit type at all its a hard coded thing to be used as a call for the email
        ///
        /// This service adds an email template to the system
        /// </summary>
        /// <param name="ViewModel"></param>
        public void AddEmailTemplate(EmailTemplateViewModel ViewModel)
        {
            EmailTemplateType type = new EmailTemplateType()
            {
                Key        = ViewModel.Key,
                Name       = ViewModel.Name,
                CreatedBy  = System.Security.Principal.WindowsIdentity.GetCurrent().Name,
                CreatedOn  = DateTime.Now,
                ModifiedBy = System.Security.Principal.WindowsIdentity.GetCurrent().Name,
                ModifiedOn = DateTime.Now
            };

            EmailTemplate template = new EmailTemplate()
            {
                EmailFrom  = ViewModel.From,
                Template   = ViewModel.Template,
                Subject    = ViewModel.Subject,
                CreatedBy  = System.Security.Principal.WindowsIdentity.GetCurrent().Name,
                CreatedOn  = DateTime.Now,
                ModifiedBy = System.Security.Principal.WindowsIdentity.GetCurrent().Name,
                ModifiedOn = DateTime.Now
            };

            db.EmailTemplateTypes.Add(type);
            db.SaveChanges();
            template.TypeId = type.Id;
            db.EmailTemplates.Add(template);
            db.SaveChanges();
        }
Exemple #5
0
 public async Task <EmailTemplate> GetTemplate(EmailTemplateType type)
 {
     return(await _requestProvider.BuildUpon(_url)
            .Uri($"/api/email/template/{(int)type}")
            .AddInterceptor(new JsonDeserializerInterceptor())
            .Execute <EmailTemplate>());
 }
 /// <summary>
 /// Replace tokens in <paramref name="EmailTemplateType"/> template using 
 /// values from arguments.
 /// </summary>
 public MailMessage Replace(EmailTemplateType emailTemplateType, params object[] args)
 {
     var message = EmailTokenReplacer.CreateMessage(
         EmailTemplateFetcher.GetBy(emailTemplateType), args
         );
     return message;
 }
        public async Task SendEmail(string subject, string to, string name, EmailTemplateType emailTemplateType, [Optional] string additinalData)
        {
            if (name == null || name.Trim() == "" || name.Length <= 2)
            {
                name = "Visitor!";
            }

            var apiKey = _configuration.GetSection("MailSettings")["SendGridApiKey"];
            var client = new SendGridClient(apiKey);
            var from   = new EmailAddress(_configuration.GetSection("MailSettings")["From"],
                                          _configuration.GetSection("MailSettings")["FiendlyName"]);
            var htmlContent      = string.Empty;
            var toAddress        = new EmailAddress(to);
            var plainTextContent = "and easy to do anywhere, even with C#";

            switch (emailTemplateType)
            {
            case EmailTemplateType.THANKS_GIVING:
                htmlContent = _configuration.GetSection("MailTemplates")["ThanksGivingMail"].Replace("##FIRSTNAME##", name);
                break;

            case EmailTemplateType.CONTACT_FORM_RECEIVED:
                htmlContent = _configuration.GetSection("MailTemplates")["NotifyMailToAdmin"] + "<br /><br />" + additinalData;
                break;
            }
            var msg      = MailHelper.CreateSingleEmail(from, toAddress, subject, plainTextContent, htmlContent);
            var response = await client.SendEmailAsync(msg);
        }
        public async Task <string> UpdateEmailTemplate(EmailTemplateType type,
                                                       [FromBody] EmailTemplate template)
        {
            template.Type = type;
            await _masterService.UpdateEmailTemplate(template);

            return("Ok");
        }
Exemple #9
0
 private static void ValidateResult(string result, List <EmailJob> jobs,
                                    List <EmailFormattingError> errors, EmailTemplateType type)
 {
     if (jobs.Any(x => !result.Contains(x.Notification.Formatting.Subject, StringComparison.OrdinalIgnoreCase)))
     {
         errors.Add(new EmailFormattingError(Texts.Email_TemplateNormalInvalid, type));
     }
 }
Exemple #10
0
 protected async Task <bool> SendSystemEmailAsync(EmailTemplateType type, SystemEmailType emailType, params object[] formatParameters)
 {
     return(await EmailService.SendEmail(new EmailMessageModel
     {
         EmailType = type,
         Destination = WebConfigurationManager.AppSettings[emailType.ToString()],
         BodyParameters = formatParameters
     }));
 }
Exemple #11
0
 public async Task SendEmailAsync(Message message, EmailTemplateType emailTemplate)
 {
     try
     {
         var mailMessage = CreateEmailMessage(message, emailTemplate);
         await SendAsync(mailMessage);
     }
     catch (Exception ex) { throw; }
 }
    /// <summary>
    /// Compiles, caches and parses a template using RazorEngine.
    /// </summary>
    /// <param name="templateType">Type of the template.</param>
    /// <param name="anonymousType">Type of the anonymous object.</param>
    /// <param name="cachedEnabled">true to enabled caching; false otherwise</param>
    /// <returns></returns>
    public static string GetTemplate <T>(EmailTemplateType templateType, T anonymousType, bool cachedEnabled = true)
    {
        string templateName = templateType.ToString();

        if (cachedEnabled == false)
        {
            ResetCache();
        }
        // pre-compile, cache & parse the template
        return(Engine.Razor.RunCompile(templateName, null, anonymousType));
    }
 private EditEmailTemplateViewModel GetModel(EmailTemplateType type)
 {
     var template = this.emailTemplatesService.GetByType(type);
     return new EditEmailTemplateViewModel
                {
                    Id = template.Id,
                    Subject = template.Subject,
                    Text = template.Text,
                    Type = type
                };
 }
Exemple #14
0
 protected Task <bool> SendSystemEmailAsync(EmailTemplateType type, SystemEmailType emailType,
                                            params object[] formatParameters)
 {
     //return await EmailService.SendEmail(new EmailMessageModel
     //{
     //	EmailType = type,
     //	Destination = WebConfigurationManager.AppSettings[emailType.ToString()],
     //	BodyParameters = formatParameters
     //});
     return(Task.FromResult(true));
 }
Exemple #15
0
 public ActionResult DeleteEmailTemplateTypeConfirmed(EmailTemplateType emailtemplatetype, string UrlReferrer)
 {
     if (!User.CanDelete("EmailTemplateType"))
     {
         return(RedirectToAction("Index", "Error"));
     }
     db.Entry(emailtemplatetype).State = EntityState.Deleted;
     db.EmailTemplateTypes.Remove(emailtemplatetype);
     db.SaveChanges();
     return(Json("FROMPOPUP", "application/json", System.Text.Encoding.UTF8, JsonRequestBehavior.AllowGet));
 }
 /// <summary>
 /// Get <paramref name="EmailTemplate"/> as per <paramref name="EmailTemplateType"/>.
 /// </summary>
 public EmailTemplate GetBy(EmailTemplateType emailTemplateType)
 {
     var root = XElement.Load("EmailTemplates.config");
     var template = root.Elements("emailTemplate")
         .Where(x => x.Attribute("id").Value == emailTemplateType.ToString())
         .SingleOrDefault();
     if (template == null)
     {
         throw new ApplicationException($"{emailTemplateType} missing in EmailTemplates.config.");
     }
     return Convert(template);
 }
Exemple #17
0
        private static string?RenderTemplate(string template, TemplateContext context,
                                             List <EmailFormattingError> errors, EmailTemplateType type, bool noCache)
        {
            var(fluidTemplate, error) = TemplateCache.Parse(template, noCache);

            if (error != null)
            {
                errors.Add(new EmailFormattingError(error.Message, type, error.Line, error.Column));
            }

            return(fluidTemplate?.Render(context));
        }
Exemple #18
0
        public async Task <EmailTemplate> GetTemplate(EmailTemplateType type)
        {
            var param = new DynamicParameters();

            param.Add("@Type", type);

            return((await SqlMapper.QueryAsync <EmailTemplate>(_unitOfWork.Connection,
                                                               "GetEmailTemplate",
                                                               param,
                                                               commandType: CommandType.StoredProcedure,
                                                               transaction: _unitOfWork.Transaction)).FirstOrDefault());
        }
Exemple #19
0
        private static string GetTemplatePath(EmailTemplateType templateType)
        {
            var mainPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var path     = templateType switch
            {
                EmailTemplateType.ConfirmAccount => Path.Combine(mainPath, $"Templates/ConfirmAccount.html"),
                EmailTemplateType.ResetPassword => Path.Combine(mainPath, $"Templates/ResetPassword.html"),
                _ => throw new ArgumentOutOfRangeException(nameof(templateType), templateType, null)
            };

            return(path);
        }
Exemple #20
0
        private EditEmailTemplateViewModel GetModel(EmailTemplateType type)
        {
            var template = this.emailTemplatesService.GetByType(type);

            return(new EditEmailTemplateViewModel
            {
                Id = template.Id,
                Subject = template.Subject,
                Text = template.Text,
                Type = type
            });
        }
Exemple #21
0
 public ActionResult Edit(EmailTemplateType obj)
 {
     try
     {
         NSession.Update(obj);
         NSession.Flush();
     }
     catch (Exception ee)
     {
         return(Json(new { IsSuccess = false, ErrorMsg = "出错了" }));
     }
     return(Json(new { IsSuccess = true }));
 }
Exemple #22
0
        /// <summary>
        /// 根据Id获取
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public EmailTemplateType GetById(int Id)
        {
            EmailTemplateType obj = NSession.Get <EmailTemplateType>(Id);

            if (obj == null)
            {
                throw new Exception("返回实体为空");
            }
            else
            {
                return(obj);
            }
        }
Exemple #23
0
        private void CreateMessange(EmailTemplateType type, DocumentTable docuTable, ApplicationUser userTable, string templateName, string documentUri, string bodyText, string subject, string[] parameters)
        {
            var emplTable = _EmplService.FirstOrDefault(x => x.ApplicationUserId == userTable.Id);

            if (emplTable == null)
            {
                return;
            }

            string processName = String.Empty;

            if (docuTable != null)
            {
                processName = docuTable.ProcessTable.ProcessName;
            }

            EmailParameterView emailParameter = FirstOrDefaultView(x => x.SmtpServer != String.Empty);

            new Task(() =>
            {
                string absFile   = HostingEnvironment.ApplicationPhysicalPath + templateName;
                string razorText = System.IO.File.ReadAllText(absFile);

                string currentLang = Thread.CurrentThread.CurrentCulture.Name;
                CultureInfo ci     = CultureInfo.GetCultureInfo(userTable.Lang);
                Thread.CurrentThread.CurrentCulture   = ci;
                Thread.CurrentThread.CurrentUICulture = ci;
                string body = String.Empty;

                switch (type)
                {
                case EmailTemplateType.Default:
                    body = Razor.Parse(razorText, new { DocumentNum = String.Format("{0} - {1}", docuTable.DocumentNum, processName), DocumentUri = documentUri, EmplName = emplTable.FullName, BodyText = bodyText });
                    break;

                case EmailTemplateType.Comment:
                    body = Razor.Parse(razorText, new { DocumentNum = String.Format("{0} - {1}", docuTable.DocumentNum, processName), DocumentUri = documentUri, EmplName = emplTable.FullName, BodyText = bodyText, LastComment = parameters[0] });
                    break;

                case EmailTemplateType.Delegation:
                    body = Razor.Parse(razorText, new { DocumentUri = documentUri, EmplNameTo = parameters[0], EmplNameFrom = parameters[1], BodyText = bodyText });
                    break;
                }
                SendEmail(emailParameter, new string[] { userTable.Email }, new string[] { }, subject, body);

                ci = CultureInfo.GetCultureInfo(currentLang);
                Thread.CurrentThread.CurrentCulture   = ci;
                Thread.CurrentThread.CurrentUICulture = ci;
            }).Start();
        }
Exemple #24
0
        public async Task SendEmail(string to, string subject, EmailTemplateType templateType, object content)
        {
            var from           = new EmailAddress("*****@*****.**", "traba.io");
            var messageContent = TemplateUtils.FormatTemplate(templateType, content);
            var message        = new SendGridMessage()
            {
                From        = from,
                Subject     = subject,
                HtmlContent = messageContent
            };

            message.AddTo(new EmailAddress(to));
            await _sendGridClient.SendEmailAsync(message);
        }
Exemple #25
0
 public JsonResult Create(EmailTemplateType obj)
 {
     try
     {
         obj.Enable = 1;
         NSession.SaveOrUpdate(obj);
         NSession.Flush();
     }
     catch (Exception ee)
     {
         return(Json(new { IsSuccess = false, ErrorMsg = "出错了" }));
     }
     return(Json(new { IsSuccess = true }));
 }
Exemple #26
0
 public JsonResult DeleteConfirmed(int id)
 {
     try
     {
         EmailTemplateType obj = GetById(id);
         NSession.Delete(obj);
         NSession.Flush();
     }
     catch (Exception ee)
     {
         return(Json(new { IsSuccess = false, ErrorMsg = "出错了" }));
     }
     return(Json(new { IsSuccess = true }));
 }
Exemple #27
0
 protected Task <bool> SendEmailAsync(ApplicationUserManager userManager, EmailTemplateType type,
                                      int?systemIdentifier, string destination, string userid, params object[] formatParameters)
 {
     //var emailParameters = new List<object>();
     //emailParameters.Add(Request.GetIPAddress()); // add ip address
     //emailParameters.AddRange(formatParameters);
     //emailParameters.Add(Url.Action("LockAccount", "Login", new { userId = userid, token = await userManager.GenerateUserTokenAsync("LockAccount", userid) }, protocol: Request.Url.Scheme));
     //return await EmailService.SendEmail(new EmailMessageModel
     //{
     //	EmailType = type,
     //	Destination = destination,
     //	SystemIdentifier = systemIdentifier,
     //	BodyParameters = emailParameters.ToArray()
     //});
     return(Task.FromResult(true));
 }
Exemple #28
0
        // GET: EmailTemplate
        public ActionResult Index()
        {
            if (!this.services.Authorizer.Authorize(Permissions.BasicDataPermission, T("Not authorized to list users")))
            {
                return(new HttpUnauthorizedResult());
            }

            var emailTempalates = this.emailTemplateRepository.Table.ToList();

            var model = emailTempalates.Select(c => new EmailTemplateViewModel
            {
                EmailTemplateId = c.Id,
                Name            = c.Name,
                TypeId          = c.TypeId,
                Subject         = c.Subject,
                Text            = c.Body,
                TypeName        = Enum.GetName(typeof(EmailTemplateType), c.TypeId)
            }).ToList();

            foreach (var template in model)
            {
                EmailTemplateType templateType = (EmailTemplateType)template.TypeId;
                switch (templateType)
                {
                case EmailTemplateType.TicketCreated:
                    template.TypeName = EmailTemplateTypeNames.TicketCreatedName;
                    break;

                case EmailTemplateType.TicketClosed:
                    template.TypeName = EmailTemplateTypeNames.TicketClosededName;
                    break;

                case EmailTemplateType.NewMessage:
                    template.TypeName = EmailTemplateTypeNames.NewMessageName;
                    break;

                case EmailTemplateType.TicketAssignedToUser:
                    template.TypeName = EmailTemplateTypeNames.TicketAssignedToUserName;
                    break;

                default:
                    break;
                }
            }

            return(this.View(model));
        }
 /// <summary>
 /// Get email template by template type
 /// </summary>
 /// <param name="emailTemplateType">Email template type</param>
 /// <returns>Email template</returns>
 public EmailTemplate GetByType(EmailTemplateType emailTemplateType)
 {
     if (emailTemplateType == EmailTemplateType.IAVWelcome)
     {
         return(Repository.Table <EmailTemplate>().FirstOrDefault(m => m.EmailTemplateType == emailTemplateType));
     }
     else if (emailTemplateType == EmailTemplateType.MicroDepositWelcome)
     {
         return(Repository.Table <EmailTemplate>().FirstOrDefault(m => m.EmailTemplateType == emailTemplateType));
     }
     else if (emailTemplateType == EmailTemplateType.IncompleteNewMemberEnrollment)
     {
         return(Repository.Table <EmailTemplate>().FirstOrDefault(m => m.EmailTemplateType == emailTemplateType));
     }
     else if (emailTemplateType == EmailTemplateType.OneYearRenewalApproaching)
     {
         return(Repository.Table <EmailTemplate>().FirstOrDefault(m => m.EmailTemplateType == emailTemplateType));
     }
     else if (emailTemplateType == EmailTemplateType.OneYearRenewal)
     {
         return(Repository.Table <EmailTemplate>().FirstOrDefault(m => m.EmailTemplateType == emailTemplateType));
     }
     else if (emailTemplateType == EmailTemplateType.AccountCancellation)
     {
         return(Repository.Table <EmailTemplate>().FirstOrDefault(m => m.EmailTemplateType == emailTemplateType));
     }
     else if (emailTemplateType == EmailTemplateType.PasswordReset)
     {
         return(Repository.Table <EmailTemplate>().FirstOrDefault(m => m.EmailTemplateType == emailTemplateType));
     }
     else if (emailTemplateType == EmailTemplateType.NotificationAccountVerify)
     {
         return(Repository.Table <EmailTemplate>().FirstOrDefault(m => m.EmailTemplateType == emailTemplateType));
     }
     else if (emailTemplateType == EmailTemplateType.Pinupdated)
     {
         return(Repository.Table <EmailTemplate>().FirstOrDefault(m => m.EmailTemplateType == emailTemplateType));
     }
     else if (emailTemplateType == EmailTemplateType.PasswordUpdate)
     {
         return(Repository.Table <EmailTemplate>().FirstOrDefault(m => m.EmailTemplateType == emailTemplateType));
     }
     else
     {
         return(null);
     }
 }
Exemple #30
0
        private void SendEmailToAdmin(List <FamilyMember> familyMembers, EmailTemplateType emailTemplateType, EmailType emailType)
        {
            var emailTemplate = _emailTemplateService.GetByType(emailTemplateType);

            foreach (var member in familyMembers)
            {
                if (member.IsUnSubscribed)
                {
                    continue;
                }

                // Send email
                _emailService.Send(member.User.Email, emailTemplate.Subject, emailTemplate.Content);
                // Save email history
                _emailHistoryService.SaveEmailHistory(member.Id, emailType);
            }
        }
        public VerificationCode(Guid?applicationId, string emailAddress, string phoneNumber, string customData = "",
                                EmailTemplateType emailTemplate = EmailTemplateType.None, EmailTemplateType smsTemplate = EmailTemplateType.None)
        {
            TimeOut = RaaiVanSettings.Users.TwoStepAuthenticationTimeout(applicationId);

            _ApplicationID = applicationId;
            _Token         = PublicMethods.random_string(20);
            reset_code();
            _EmailAddress = emailAddress;
            _PhoneNumber  = phoneNumber;
            _TTL          = 3;

            _EmailTemplate = emailTemplate == EmailTemplateType.None ? EmailTemplateType.ConfirmationCode : emailTemplate;
            _SMSTemplate   = smsTemplate == EmailTemplateType.None ? EmailTemplateType.ConfirmationCodeSMS : smsTemplate;

            _CustomData = customData;
        }
Exemple #32
0
        public static string FormatTemplate(EmailTemplateType templateType, object content)
        {
            var path = GetTemplatePath(templateType);

            var builder = new StringBuilder();

            using var reader = File.OpenText(path);
            builder.Append(reader.ReadToEnd());

            var properties = content.GetType().GetProperties();

            foreach (var propertyInfo in properties)
            {
                builder.Replace($"{{{{{propertyInfo.Name}}}}}", propertyInfo.GetValue(content).ToString());
            }

            return(builder.ToString());
        }
        public async Task <EmailSetting> GetTemplateAndEmailParameterAsync(EmailTemplateType templateType)
        {
            var entity = await _dal.TableNoTracking.Include(x => x.EmailParameter).FirstOrDefaultAsync(x => x.TemplateType == templateType);

            return(new EmailSetting
            {
                Subject = entity?.Title ?? "",
                Body = entity?.MessageTemplate ?? "",
                EmailOptions = new EmailOptions
                {
                    UserName = entity?.EmailParameter?.UserName ?? "",
                    Password = entity?.EmailParameter?.Password ?? "",
                    SmtpServer = entity?.EmailParameter?.SmtpServer ?? "",
                    Port = entity?.EmailParameter?.Port ?? 0,
                    EnableSsl = entity?.EmailParameter?.EnableSsl ?? false
                }
            });
        }
Exemple #34
0
 public bool SendMessage(EmailTemplateType type, Client client, string text = null)
 {
     var template = this.emailTemplatesService.GetByType(type);
     var body = template.Text;
     var subject = template.Subject;
     if (!string.IsNullOrEmpty(text))
     {
         body = body.Replace("{text}", text);
     }
     subject = subject.Replace("{firstname}", client.FirstName);
     body = this.MassReplace(
         body,
         new Collection<KeyValuePair<string, string>> {
             new KeyValuePair<string, string>("{firstname}", client.FirstName),
             new KeyValuePair<string, string>("{lastname}", client.LastName),
             new KeyValuePair<string, string>("{time}", DateTime.Now.ToShortTimeString()),
             new KeyValuePair<string, string>("{date}", DateTime.Now.ToShortDateString()),
             new KeyValuePair<string, string>("{currentamount}", client.PrimaryAccount.Amount.ToString("C0"))
         });
     subject = subject.Replace("{lastname}", client.FirstName);
     return this.SendMessage(subject, body, client.Email);
 }
 public EmailTemplate GetByType(EmailTemplateType type)
 {
     var template = this.emailTemplatesRepository.GetByType(type);
     return template ?? new EmailTemplate();
 }
 /// <summary>
 /// Get <paramref name="EmailTemplate"/> as per <paramref name="EmailTemplateType"/>.
 /// </summary>
 public EmailTemplate GetBy(EmailTemplateType emailTemplateType)
 {
     // implementation goes here.
     throw new NotImplementedException();
 }
Exemple #37
0
		public void SendPeriodicalNotification(EmailTemplateType template, Dictionary<string, string> replaceDictionary, string[] emailsTo, string[] emailsCC)
		{
			string emailsToString = string.Join(",", emailsTo);
			string emailsCCString = string.Empty;
			if (emailsCC != null)
				emailsCCString = string.Join(",", emailsCC);
			string emailFrom = _configManager.OrderManagementEmailFrom;
			SendMailInternal(template, emailsToString, replaceDictionary, emailsCCString, emailFrom);
		}
Exemple #38
0
		private void SendMailInternal(EmailTemplateType emailTemplateType, string emailsTo, Dictionary<string, string> dic = null, string emailsCC = null, string emailFrom = null)
		{
			if (string.IsNullOrWhiteSpace(emailsTo))
				throw new ArgumentNullException("email cannot be null or empty");

			var template = _emailRepository.GetByEmailTemplateType(emailTemplateType);
			StringBuilder body = CreateHTMLMailBody();
			body.Replace(Constants.EmailTemplateKeyWords.MailBody, template.Body);
			StringBuilder subject = new StringBuilder(template.Subject);
			StringBuilder signature = new StringBuilder(template.Signature);
			if (dic != null)
			{
				foreach (var item in dic)
				{
					body.Replace(item.Key, item.Value);
					subject.Replace(item.Key, item.Value);
				}
			}

			MailMsg msg = new MailMsg();

			signature.Replace(Constants.EmailTemplateKeyWords.ContactUsLink, _configManager.WebSiteBaseURL + Constants.WebSiteUrls.ContactUs);

			if (template.Signature.Contains(Constants.EmailTemplateKeyWords.SignatureLogo))
			{
				string contentId = AddLogoAsAttachment(msg);
				signature.Replace(Constants.EmailTemplateKeyWords.SignatureLogo, "cid:" + contentId);
			}

			body.Replace(Constants.EmailTemplateKeyWords.MailSignature, signature.ToString());

			msg.IsBodyHtml = true;
			msg.Body = body.ToString();
			msg.Subject = subject.ToString();
			if (!string.IsNullOrWhiteSpace(emailFrom))
				msg.From = new MailAddress(emailFrom);
			else
				msg.From = new MailAddress(_configManager.EmailFrom);

			if (!string.IsNullOrWhiteSpace(_configManager.AlternativeEmail))
				msg.To.Add(_configManager.AlternativeEmail);
			else
				msg.To.Add(emailsTo);
			if (!string.IsNullOrWhiteSpace(emailsCC) && string.IsNullOrWhiteSpace(_configManager.AlternativeEmail))
				msg.CC.Add(emailsCC);

			msg.Send();

		}