I have been looking into stuff like method chaining, Cascade-Lambda pattern etc.
I have created a class which seems to work fine. However, I just wanted to confirm if this is the best way and the right way to implement this.
For the cascade lambda pattern I was unable to use Action action as a parameter to the Send() method. I couldn't figure out how would I use it.
Any suggestions are welcome.
Here is the code:
public class MailManager
{
MailMessage _mail { get; set; }
SmtpClient _smtp { get; set; }
public MailManager()
{
_mail = new MailMessage();
_smtp = new SmtpClient();
}
public MailManager To(string address)
{
_mail.From = new MailAddress(address);
return this;
}
public MailManager From(string address)
{
_mail.To.Add(new MailAddress(address));
return this;
}
public MailManager Subject(string subject)
{
_mail.Subject = subject;
return this;
}
public MailManager Body(string body)
{
_mail.Body = body;
return this;
}
public MailManager IsBodyHtml(bool isBodyHtml = true)
{
_mail.IsBodyHtml = isBodyHtml;
return this;
}
public MailManager AlternateViews(AlternateView alternateView)
{
_mail.AlternateViews.Add(alternateView);
return this;
}
public MailManager Host(string host)
{
_smtp.Host = host; return this;
}
public MailManager Port(int port)
{
_smtp.Port = port; return this;
}
public MailManager Credentials(NetworkCredential credentials)
{
_smtp.Credentials = credentials; return this;
}
public MailManager EnableSsl(bool enableSsl = true)
{
_smtp.EnableSsl = enableSsl; return this;
}
public void Send()
{
using (_smtp)
{
_smtp.Send(_mail);
}
}
}
This is how I use it:
mailManager.From(_emailSettings.Email)
.To(item.Email)
.Subject(string.Format(_emailSettings.Subject, item.Name)).AlternateViews(htmlView)
.Body(body).IsBodyHtml()
.Host(_emailSettings.Domain)
.Port(_emailSettings.Port)
.Credentials(new NetworkCredential(_emailSettings.Email, _emailSettings.Password))
.EnableSsl()
.Send();
To
andFrom
should return new instances, the cost isn't too big and the bugs hen people make assumptions about it are terrible - that's why things like DateTime or strings don't mutate but return DateTimes (or strings). \$\endgroup\$EmailBuilder
. \$\endgroup\$