Skip to content

Small and simple abstraction around System.Net.Mail.SmtpClient

License

Notifications You must be signed in to change notification settings

gavynriebau/System.Net.Mail.Abstractions

Repository files navigation

System.Net.Mail.Abstractions

Inspired by System.IO.Abstractions and System.Configuration.Abstractions comes System.Net.Mail.Abstractions. A small and simple abstraction around SmtpClient to help you write TDD focused code.

Install

PM> Install-Package System.Net.Mail.Abstractions

Register

var builder = new ContainerBuilder();

// Register ISmtpClient using your favourite DI container
builder.RegisterInstance(new SmtpClient()).As<ISmtpClient>();

// Register other dependencies
// ...

var container = builder.Build();

Consume

public class MyClass
{
   private ISmtpClient _smtpClient;

   public MyClass(ISmtpClient smtpClient)
   {
       _smtpClient = smtpClient;
   }

   public void DoSomethingThenSendEmail()
   {
       // ...

       if (true)
       {
           var from = "[email protected]";
           var recipients = "[email protected]";
           var subject = "Extreme warning";

           var body = new StringBuilder()
               .AppendLine("Dear Manager,")
               .AppendLine("")
               .AppendLine("The plant is about to explode")
               .AppendLine("")
               .AppendLine("Kind Regards,")
               .AppendLine("The System")
               .ToString();

           _smtpClient.Send(from, recipients, subject, body); 
       }

       // ...
   }
}

Test

[TestFixture]
public class MyClassTests
{
    [Test]
    public void MyClass_WhenSomeCondition_SendsEmail()
    {
        // Arrange.
        var smtpClient = Substitute.For<ISmtpClient>(); // Using NSubstitute to create a mock of ISmtpClient.
        var sut = new MyClass(smtpClient);              // Pass in the mocked class

        // Act.
        sut.DoSomethingThenSendEmail();

        // Assert.
        // Ensure ISmtpClient.Send was called
        smtpClient.Received(1).Send("[email protected]", "[email protected]", "Extreme warning", Arg.Any<string>());
    }
}

About

Small and simple abstraction around System.Net.Mail.SmtpClient

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages