I have the below method that is responsible for generating and sending a MailMessage
using a SmtpClient
object:
public static void SendEmail(
string subject,
string body,
bool isBodyHtml,
List<string> emails,
List<string> ccs = null)
{
if (emails == null)
{
throw new ArgumentNullException("emails");
}
MailMessage message = new MailMessage
{
Subject = subject,
Body = body,
IsBodyHtml = isBodyHtml
};
foreach (string email in emails)
{
message.To.Add(email);
}
if (ccs != null)
{
foreach (string cc in ccs)
{
message.CC.Add(cc);
}
}
SmtpClient client = new SmtpClient
{
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network
};
client.Send(message);
}
But recently I've been reading more on S.O.L.I.D and principles of OOP design, so I thought to refactor this method, and compartmentalize it more.
Am I on the right track with my refactor? Are there ways to make my code more modular/testable?
Here's my refactored code:
private static MailMessage CreateMailMessage(
string subject,
string body,
bool isBodyHtml,
List<string> emails,
List<string> ccs = null)
{
if (emails == null)
{
throw new ArgumentNullException("emails");
}
MailMessage message = new MailMessage
{
Subject = subject,
Body = body,
IsBodyHtml = isBodyHtml
};
foreach (string email in emails)
{
message.To.Add(email);
}
if (ccs != null)
{
foreach (string cc in ccs)
{
message.CC.Add(cc);
}
}
return message;
}
private static SmtpClient CreateSmtpClient(
bool enableSsl,
SmtpDeliveryMethod deliveryMethod)
{
SmtpClient client = new SmtpClient
{
EnableSsl = enableSsl,
DeliveryMethod = deliveryMethod
};
return client;
}
And here's the method responsible for calling the above two and sending the email:
public static void SendEmail(string subject, string body, List<string> emails, List<string> ccs = null)
{
using (MailMessage message = CreateMailMessage(subject, body, true, emails, ccs))
{
using (SmtpClient client = CreateSmtpClient(true, SmtpDeliveryMethod.Network))
{
client.Send(message);
}
}
}