In my project I need to send emails. Emails will have different credentials and senders. I'm thinking about "abstract factory", but will it be good solution?
public abstract class Mail
{
public string Body { get; protected set; }
public string Subject { get; private set; }
public string EmailTo { get; private set; }
protected Mail(string subject, string emailTo)
{
this.Subject = subject;
this.EmailTo = emailTo;
}
protected abstract void BuildBody();
}
public class AccountMail : Mail
{
private string _firstName;
private string _lastName;
private string _email;
private string _siteDomain;
public AccountMail(string subject, string emailTo, string firstName, string lastName, string siteDomain, string email): base(subject, emailTo)
{
_firstName = firstName;
_lastName = lastName;
_email = email;
_siteDomain = siteDomain;
BuildBody();
}
protected override sealed void BuildBody()
{
StringBuilder bodyBuilder = new StringBuilder();
base.Body = bodyBuilder.ToString();
}
That is abstract Mail
and concrete Mail
. Do I really need abstract MailSender
and concrete MailSender
for each email? This is quick solution, because I needed this functionality right now. It's working like this:
public abstract class MailSender
{
public abstract void SendMail(string subject, string emailTo, string firstName, string lastName);
}
public class AccountMailSender : MailSender
{
public override void SendMail(string subject, string emailTo, string firstName, string lastName)
{
AccountMail mail = new AccountMail(subject, emailTo, firstName, lastName, "");
Task.Factory.StartNew(() =>
{
MailMessage mailMessage = new MailMessage(ConfigSettings.EmailFrom, mail.EmailTo, mail.Subject, mail.Body);
mailMessage.IsBodyHtml = true;
SmtpClient client = new SmtpClient(ConfigSettings.EmailServer, ConfigSettings.EmailPort);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(ConfigSettings.EmailUser, ConfigSettings.EmailPassword);
try
{
client.Send(mailMessage);
}
catch
{
}
});
}
}
I know that it's bad and that I need to refactor, but I also need your advice.