Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //////////// Interfaces
- public interface ICustomSystemEmailService
- {
- /// <summary>
- /// Will send an email out using, replacing {% PropertyName %} values with the values found in the ICustomSystemEmailTemplate class.
- /// A general {% Body %} macro can be used and the body content will be placed in that macro if provided
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="emailProperties">The model that has properties that match the macro names of the email template</param>
- /// <param name="emailMessage">The basic email message. The body will be replaced with the given template. If the macro {% body %} is present in the template and the emailMessage has content in it's body, it will put that in there.</param>
- /// <returns></returns>
- Task SendEmail<T>(T emailProperties, EmailMessage emailMessage) where T : ICustomSystemEmailTemplate;
- }
- public interface ICustomSystemEmailTemplate
- {
- string EmailLibraryEmailTemplateName { get; }
- }
- ////////// Implementation
- public partial class CustomSystemEmailService(IProgressiveCache progressiveCache,
- IInfoProvider<EmailTemplateInfo> emailTemplateInfoProvider,
- IEmailService emailService) : ICustomSystemEmailService
- {
- private readonly IProgressiveCache _progressiveCache = progressiveCache;
- private readonly IInfoProvider<EmailTemplateInfo> _emailTemplateInfoProvider = emailTemplateInfoProvider;
- private readonly IEmailService _emailService = emailService;
- public async Task SendEmail<T>(T emailProperties, EmailMessage emailMessage) where T : ICustomSystemEmailTemplate
- {
- var macroResolver = MacroResolver.GetInstance(false);
- var data = new Dictionary<string, object>();
- var body = emailMessage.Body;
- var templateName = emailProperties.EmailLibraryEmailTemplateName;
- // get the email template
- var bodyContent = await _progressiveCache.LoadAsync(async cs => {
- if (cs.Cached) {
- cs.CacheDependency = CacheHelper.GetCacheDependency([$"{EmailTemplateInfo.OBJECT_TYPE}|byname|{templateName}"]);
- }
- var items = (await _emailTemplateInfoProvider.Get().WhereEquals(nameof(EmailTemplateInfo.EmailTemplateName), templateName).GetEnumerableTypedResultAsync());
- var templateCode = items.FirstOrMaybe().TryGetValue(out var item) ? item.EmailTemplateCode : "<!DOCTYPE html><html><head></head><body>{% body %}</body></html>";
- return templateCode.Replace("{%body%}", "{% body %}", StringComparison.OrdinalIgnoreCase).Replace("{% body %}", "{% body |(encode)false %}", StringComparison.OrdinalIgnoreCase);
- }, new CacheSettings(CacheMinuteTypes.Short.ToDouble(), nameof(CustomSystemEmailService),"GetEmailTemplateByName", templateName));
- foreach (var property in typeof(T).GetProperties()) {
- if(!property.Name.Equals(nameof(ICustomSystemEmailTemplate.EmailLibraryEmailTemplateName))) {
- var value = property.GetValue(emailProperties);
- if(value !=null) {
- data.TryAdd(property.Name, value);
- } else {
- data.TryAdd(property.Name, string.Empty);
- }
- }
- }
- // Add body
- if(!data.ContainsKey("body")) {
- data.Add("body", body.GetValueOrDefault(string.Empty));
- }
- macroResolver.SetNamedSourceData(data);
- var messageHtml = macroResolver.ResolveMacros(bodyContent);
- // Clone and send
- var newMessage = new EmailMessage() {
- //Attachments = emailMessage.Attachments,
- BccRecipients = emailMessage.BccRecipients,
- CcRecipients = emailMessage.CcRecipients,
- EmailFormat = emailMessage.EmailFormat,
- From = emailMessage.From,
- Guid = emailMessage.Guid,
- //Headers = emailMessage.Headers,
- MailoutGuid = emailMessage.MailoutGuid,
- Priority = emailMessage.Priority,
- Recipients = emailMessage.Recipients,
- ReplyTo = emailMessage.ReplyTo,
- Subject = emailMessage.Subject
- };
- switch(emailMessage.EmailFormat) {
- case EmailFormatEnum.Both:
- newMessage.Body = messageHtml;
- newMessage.PlainTextBody = HttpUtility.HtmlDecode(HtmlStripRegex().Replace(messageHtml, string.Empty));
- break;
- case EmailFormatEnum.PlainText:
- newMessage.PlainTextBody = HttpUtility.HtmlDecode(HtmlStripRegex().Replace(messageHtml, string.Empty));
- break;
- case EmailFormatEnum.Html:
- newMessage.Body = messageHtml;
- break;
- }
- foreach (var headerKey in emailMessage.Headers.AllKeys) {
- newMessage.Headers.Add(headerKey, emailMessage.Headers[headerKey]);
- }
- foreach (var attachment in emailMessage.Attachments) {
- newMessage.Attachments.Add(attachment);
- }
- // Send out
- await _emailService.SendEmail(newMessage);
- return;
- }
- [GeneratedRegex("<.*?>")]
- private static partial Regex HtmlStripRegex();
- }
- ///////////////////////////// Email Template "Model"
- public class ClientTokenAuthenticationEmailTemplate : ICustomSystemEmailTemplate
- {
- public ClientTokenAuthenticationEmailTemplate(string authenticationUrl, string memberFullName)
- {
- AuthenticationUrl = authenticationUrl;
- MemberFullName = memberFullName;
- }
- // This is the Email Template Code Name
- public string EmailLibraryEmailTemplateName => "ClientTokenAuthenticationEmailTemplate";
- public string AuthenticationUrl { get; set; }
- public string MemberFullName { get; set; }
- }
- ///////////////////// Usage
- var tokenGuid = await _clientRepository.GetAuthToken(client.Identity.Value.Id, false);
- // The Guid (token) should now be set
- var emailModel = new ClientTokenAuthenticationEmailTemplate(
- authenticationUrl: $"https://www.mysite.com/client/token-authenticate?token={tokenGuid}{(redirectUrl.AsNullOrWhitespaceMaybe().TryGetValue(out var redirectUrlVal) ? $"&returnUrl={HttpUtility.UrlEncode(redirectUrlVal)}" : "")}",
- memberFullName: $"{client.FirstName} {client.LastName}");
- await _customSystemEmailService.SendEmail(emailModel, new EmailMessage() {
- From = EmailConstants._NoReplyEmailAddress,
- Subject = "Temporary Authentication Token",
- Recipients = client.Email,
- EmailFormat = EmailFormatEnum.Both,
- });
- /////////////////////// Email template Content
- <!DOCTYPE html>
- <html>
- <head></head>
- <body>
- <p>{%MemberFullName%},</p>
- <p>Since your account does not have a user login, in order to proceed please use the link below to temporarily authenticate.</p>
- <p><a href="{%AuthenticationUrl%}">{%AuthenticationUrl%}</a></p>
- <p>This token is only valid for 1 hour, or until leveraged and then logged out. If you did not request this, please disregard and delete this email.</p>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment