You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
92 lines
2.6 KiB
C#
92 lines
2.6 KiB
C#
4 years ago
|
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"])
|
||
|
};
|
||
|
}
|
||
|
|
||
|
}
|
||
|
}
|