Table of Contents

Quick Start

The following few simple steps will bring Mailtrap API functionality into your .NET project.

Prerequisites

Please ensure your project targets .NET implementation which supports .NET Standard 2.0 specification.

Setup

  • Install Mailtrap package from NuGet

    TODO
    This is an example command, to be updated once the package is published.

    dotnet add package Mailtrap
    
  • Register new or log into existing account at mailtrap.io

  • Obtain API token
    You can use one of the existing or create a new one.

Configure

Mailtrap API client supports few configuration options.

If you are using a hosting model from Microsoft in your app (IHostBuilder, IWebHostBuilder, etc.), you can simply add Mailtrap API client to host DI container:

using Mailtrap;
   
...
   
hostBuilder.ConfigureServices((context, services) =>
{
   services.AddMailtrapClient(options =>
   {
      // Definitely, hardcoding a token isn't a good idea.
      // This example uses it for simplicity, but in real-world scenarios
      // you should consider more secure approaches for storing secrets.
         
      // Environment variables can be an option, as well as other solutions:
      // https://learn.microsoft.com/aspnet/core/security/app-secrets
      // or https://learn.microsoft.com/aspnet/core/security/key-vault-configuration
      options.ApiToken = "<API_TOKEN>";
   });
});   

And after that you can inject IMailtrapClient instances in any application service:

using Mailtrap;
   
...

public SomeCoolApplicationService(IMailtrapClient client)
{
   mailtrapClient = client;
}
Note

The detailed configuration guide with more advanced setup scenarios can be found here.

Use

Finally, when you have obtained IMailtrapClient instance, you can use it to make API calls:

using Mailtrap.Emails.Requests;
using Mailtrap.Emails.Responses;

...

try 
{
   SendEmailRequest request = SendEmailRequest
      .Create()
      .From("john.doe@demomailtrap.com", "John Doe")
      .To("hero.bill@galaxy.net")
      .Subject("Invitation to Earth")
      .Text("Dear Bill,\n\nIt will be a great pleasure to see you on our blue planet next weekend.\n\nBest regards, John.");

   SendEmailResponse response = await mailtrapClient
      .Email()
      .Send(request);
      
   string messageId = response.MessageIds.FirstOrDefault();
}
catch (MailtrapException mtex)
{
   // handle Mailtrap API specific exceptions
}
catch (OperationCancelledException ocex)
{
   // handle cancellation
}
catch (Exception ex)
{
   // handle other exceptions
}   

What's next

Please visit Configuration section for more configuration examples.

Various client usage examples and recipes can be found in Cookbook.

Also a bunch of examples is available in the Source Repository.

Detailed API reference is available here.