using System.Net.Mail; using System.Collections.Generic; using System; using Microsoft.Extensions.Configuration; using System.Linq; namespace Common.Library.Email { public class SendEmail { private EmailConfig _config; public SendEmail(EmailConfig config) { _config = config; } public void Send() { MailMessage message = null; try { message = GetMessage(); SmtpClient mailClient = new(_config.SMTPServer, _config.SMTPServerPort); mailClient.Send(message); } catch (Exception) { throw; } finally { if(message != null) { message.Dispose(); } } } public void Send(EmailConfig config) { _config = config; Send(); } private MailMessage GetMessage() { MailMessage message = new() { Subject = _config.Subject, Body = _config.Body, From = new(_config.From), IsBodyHtml = _config.IsHtml }; message.AddTo(_config.To); message.AddCC(_config.CC); message.AddBCC(_config.BCC); return message; } } public class EmailConfig { public string From { get; set; } public List To { get; set; } public List BCC { get; set; } public List CC { get; set; } public string Subject { get; set; } public string Body { get; set; } public bool IsHtml { get; set; } public string SMTPServer { get; set; } public int SMTPServerPort { get; set; } public static EmailConfig GetEmailConfig(IConfiguration configuration) { return new() { To = configuration?.GetSection("Email:To").Get>(), BCC = configuration?.GetSection("Email:BCC").Get>(), CC = configuration?.GetSection("Email:CC").Get>(), Subject = configuration?.GetSection("Email")["Subject"], IsHtml = bool.Parse(configuration?.GetSection("Email")["IsHtml"]), SMTPServer = configuration?.GetSection("Email")["SMTPServer"], SMTPServerPort = int.Parse(configuration?.GetSection("Email")["SMTPServerPort"]) }; } } }