I have an application that has to be able to send emails to users. I thought that creating SmtpClient
every time a new email will be sent, like so using(smtpClient = new SmtpClient()) {// logic to send email}
is redundant so I thought, I would create one instance of SmtpClient
and reuse it throughout application lifecycle.
This is a helper class I created to do so, this class will have one instance per application and as a consequence the same instance of SmtpClient
will be used all the time:
public class MailHelper : IMailHelper
{
private readonly SmtpClient _smtpClient = new SmtpClient();
public void SendMail(string recipient, string subject, string body, string attachmentContent = null, string attachmentName = null)
{
var mail = new MailMessage();
mail.To.Add(new MailAddress(recipient));
mail.Subject = subject;
mail.Body = body;
if (attachmentContent != null && attachmentName != null)
mail.Attachments.Add(Attachment.CreateAttachmentFromString(attachmentContent, attachmentName));
_smtpClient.Send(mail);
}
}
Is it a good approach to do so? Do you see any pitfalls with it?