|
| 1 | +using Core.Data; |
| 2 | +using Microsoft.Extensions.Configuration; |
| 3 | +using Microsoft.Extensions.Logging; |
| 4 | +using SendGrid; |
| 5 | +using SendGrid.Helpers.Mail; |
| 6 | +using System.Collections.Generic; |
| 7 | +using System.Threading.Tasks; |
| 8 | + |
| 9 | +namespace Core.Services |
| 10 | +{ |
| 11 | + public interface ISendGridService |
| 12 | + { |
| 13 | + Task SendNewsletters(PostItem postItem, List<string> emails); |
| 14 | + Task SendEmail(string to, string subject, string content); |
| 15 | + } |
| 16 | + |
| 17 | + public class SendGridService : ISendGridService |
| 18 | + { |
| 19 | + private readonly IConfiguration _config; |
| 20 | + private readonly ILogger _logger; |
| 21 | + |
| 22 | + public SendGridService(IConfiguration config, ILogger<SendGridService> logger) |
| 23 | + { |
| 24 | + _config = config; |
| 25 | + _logger = logger; |
| 26 | + } |
| 27 | + |
| 28 | + public async Task SendNewsletters(PostItem postItem, List<string> emails) |
| 29 | + { |
| 30 | + foreach (var email in emails) |
| 31 | + { |
| 32 | + var subject = "Newsletter: " + postItem.Title; |
| 33 | + var htmlContent = postItem.Description; |
| 34 | + |
| 35 | + await SendEmail(email, subject, htmlContent); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + public async Task SendEmail(string to, string subject, string content) |
| 40 | + { |
| 41 | + var section = _config.GetSection("Blogifier"); |
| 42 | + |
| 43 | + if(section != null) |
| 44 | + { |
| 45 | + var apiKey = section.GetValue<string>("SendGridApiKey"); |
| 46 | + |
| 47 | + if (!string.IsNullOrEmpty(apiKey)) |
| 48 | + { |
| 49 | + try |
| 50 | + { |
| 51 | + var client = new SendGridClient(apiKey); |
| 52 | + |
| 53 | + var fromEmail = section.GetValue<string>("SendGridEmailFrom") ?? "admin@blog.com"; |
| 54 | + var fromName = section.GetValue<string>("SendGridEmailFromName") ?? "Blog admin"; |
| 55 | + var from = new EmailAddress(fromEmail, fromName); |
| 56 | + |
| 57 | + var msg = MailHelper.CreateSingleEmail(from, new EmailAddress(to), subject, content.StripHtml(), content); |
| 58 | + var response = await client.SendEmailAsync(msg); |
| 59 | + |
| 60 | + if(response.StatusCode == System.Net.HttpStatusCode.Unauthorized) |
| 61 | + { |
| 62 | + _logger.LogError("SendGrid service returned 'Unauthorized' - please verfiy SendGrid API key in configuration file"); |
| 63 | + } |
| 64 | + } |
| 65 | + catch (System.Exception ex) |
| 66 | + { |
| 67 | + _logger.LogError(ex.Message); |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + } |
| 72 | + await Task.CompletedTask; |
| 73 | + } |
| 74 | + } |
| 75 | +} |
0 commit comments