1
\$\begingroup\$

This is a very basic Mailer service that I put together after finding out that MVC Mailer doesn't play nice with MVC 5.

public class MailerService
{
    private const string domainEmail = "admin@mydomain.com";
    private void Send(MailMessage mailMessage)
    {
        using (var smtpClient = new SmtpClient())
        {
            smtpClient.SendAsync(mailMessage,mailMessage);
            smtpClient.SendCompleted += (sender, args) =>
            {
                if (args.Error != null)
                {
                    //save it to nLog
                }
            };
        }
    }

    public void GenerateWelcome(AccountModel model)
    {
        var template = File.ReadAllText(HttpContext.Current.Server.MapPath("~/Mailer/Templates/Welcome.html"));
        var body = Engine.Razor.RunCompile(template, "Welcome", typeof(AccountModel), model);

        this.Send
        (
            new MailMessage(domainEmail, model.Email)
            {
                Body = body,
                IsBodyHtml = true,
                Subject = "Welcome"
            }
        );
    }
}

The class is newed up in a base controller like so:

        public MailerService Mailer
    {
        get { return new MailerService(); }
    }

And then is called inside IHttpAction result with one line:

Mailer.GenerateWelcome(account);

I'm really looking to learn and improve regarding building my own custom implementations of such things as SMTP client and mail message. What is a better way to implement a mailer service like this, making it more generic and testable? What can go wrong here if lets say a 100 users hit this at the same time?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.