Skip to content
andrewdavey edited this page May 30, 2012 · 4 revisions

Postal provides an EmailService class that handles creating and sending emails. It implements the following interface.

interface IEmailService {
  void Send(Email email);
  System.Threading.Tasks.Task SendAsync(Email email);
  System.Net.Mail.MailMessage CreateMailMessage(Email email);
}

The Email object has a Send method that uses the EmailService class to send itself. However, you can use the EmailService class directly. Do this when you want to just create the MailMessage object, without sending it; or if you want to mock out the sending of email in your controller.

Example

public class ExampleController : Controller {
  // Imagine we're using a funky IoC container to inject the email service instance.
  public ExampleController(IEmailService emailService) {
    this.emailService = emailService;
  }

  readonly IEmailService emailService;

  public void Send(string message) {
    dynamic email = new Email("Example");
    email.Message = message;
    emailService.Send(email);
  }

  // You don't have to call Send, you can just get the System.Net.MailMessage.
  public void Process() {
    dynamic email = new Email("AnotherExample");
    using (var message = emailService.CreateMailMessage(email)) {
      DoStufWithMessage(message);
      SendMessageWithMyOwnGateway(message);
    }
  }
}

This controller is easy to test by providing a mock IEmailService.

Clone this wiki locally