added email ability

net6.0
Don Oerkfitz 4 years ago
parent bdaeac6f3e
commit 615f79c338

@ -0,0 +1,30 @@
using System.Net.Mail;
using System.Collections.Generic;
using System.Linq;
namespace Common.Library.Email
{
public static class EmailExtensions
{
public static void AddTo(this MailMessage message, List<string> addresses)
{
addresses.ForEach(address => message.To.Add(address));
}
public static void AddBCC(this MailMessage message, List<string> addresses)
{
if(addresses != null && addresses.Count > 0)
{
addresses.ForEach(address => message.Bcc.Add(address));
}
}
public static void AddCC(this MailMessage message, List<string> addresses)
{
if(addresses != null && addresses.Count > 0)
{
addresses.ForEach(address => message.CC.Add(address));
}
}
}
}

@ -0,0 +1,92 @@
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<string> To { get; set; }
public List<string> BCC { get; set; }
public List<string> 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<List<string>>(),
BCC = configuration?.GetSection("Email:BCC").Get<List<string>>(),
CC = configuration?.GetSection("Email:CC").Get<List<string>>(),
Subject = configuration?.GetSection("Email")["Subject"],
IsHtml = bool.Parse(configuration?.GetSection("Email")["IsHtml"]),
SMTPServer = configuration?.GetSection("Email")["SMTPServer"],
SMTPServerPort = int.Parse(configuration?.GetSection("Email")["SMTPServerPort"])
};
}
}
}
Loading…
Cancel
Save