Skip to content

mailtrap/mailtrap-dotnet

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Mailtrap

GitHub Package Version CI License

Official Mailtrap .NET Client

Welcome to the official Mailtrap .NET Client repository.
This client allows you to quickly and easily integrate your .NET application with v2.0 of the Mailtrap API.


Prerequisites

To get the most out of this official Mailtrap.io .NET SDK:


Installation

The Mailtrap .NET client packages are available through GitHub Packages.

To add the GitHub Packages source to your NuGet configuration it is required to authenticate to GitHub Packages.

dotnet nuget add source https://nuget.pkg.github.com/mailtrap/index.json --name github-mailtrap --username GITHUB_USERNAME --password GITHUB_PAT --store-password-in-clear-text

Replace GITHUB_USERNAME with the username to be used when connecting to an authenticated source.

Replace GITHUB_PAT with the personal access token that is granted at least read:packages scope.

Then add the Mailtrap package:

dotnet add package Mailtrap -v 3.0.0 -s github-mailtrap

Optionally, you can add the Mailtrap.Abstractions package:

dotnet add package Mailtrap.Abstractions -v 3.0.0 -s github-mailtrap

Framework tools integration

If you are using a framework such as .NET Core, you can integrate the Mailtrap client easily through dependency injection:

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>";
    });
});

This automatically registers an IMailtrapClient instance for injection.


Usage

Minimal usage (Sending)

The simplest way to send an email with only the required parameters:

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

try
{
    var apiToken = "<API-TOKEN>";
    using var mailtrapClientFactory = new MailtrapClientFactory(apiToken);
    IMailtrapClient mailtrapClient = mailtrapClientFactory.CreateClient();
    SendEmailRequest request = SendEmailRequest
        .Create()
        .From("hello@demomailtrap.co", "Mailtrap Test")
        .To("world@demomailtrap.co")
        .Subject("You are awesome!")
        .Text("Congrats for sending test email with Mailtrap!");
    SendEmailResponse? response = await mailtrapClient
        .Email()
        .Send(request);
}
catch (MailtrapException mtex)
{
    // handle Mailtrap API specific exceptions
}
catch (OperationCanceledException ocex)
{
    // handle cancellation
}
catch (Exception ex)
{
    // handle other exceptions
}  

Sending - Testing (Sandbox vs Production)

Mailtrap allows you to switch between sandbox (testing) and production sending environments easily.

Difference: In sandbox mode, you use .Test(inboxId) instead of .Email(), and provide an inboxId.

var apiToken = "<API-TOKEN>";
var inboxId = <INBOX-ID>; // Only needed for sandbox
using var mailtrapClientFactory = new MailtrapClientFactory(apiToken);
IMailtrapClient mailtrapClient = mailtrapClientFactory.CreateClient();

SendEmailRequest request = SendEmailRequest
    .Create()
    .From("hello@demomailtrap.co", "Mailtrap Test")
    .To("world@demomailtrap.co")
    .Subject("You are awesome!")
    .Text("Congrats for sending test email with Mailtrap!");

SendEmailResponse? response = await mailtrapClient
    .Test(inboxId)
    .Send(request);

This allows you to validate sending logic without delivering actual emails to production recipients.

Bulk stream example

Bulk stream sending differs only by using .Bulk() instead of .Email():

SendEmailResponse? response = await mailtrapClient
    .Bulk()
    .Send(request);

This enables optimized delivery for large batches of transactional or marketing messages.

Full-featured example of Sending

A more advanced example showing full email sending features, including templates, attachments, and validation:

using System.Net.Mime;
using Mailtrap;
using Mailtrap.Core.Models;
using Mailtrap.Core.Validation;
using Mailtrap.Emails.Requests;
using Mailtrap.Emails.Responses;

try
{
    var apiToken = "<API-TOKEN>";
    using var mailtrapClientFactory = new MailtrapClientFactory(apiToken);
    IMailtrapClient mailtrapClient = mailtrapClientFactory.CreateClient();

    SendEmailResponse? response = await SendEmailAsync(mailtrapClient, FullyFeaturedRequest());
    Console.Out.Write(response);

    response = await SendEmailAsync(mailtrapClient, TemplateBasedRequest());
    Console.Out.Write(response);
}
catch (Exception ex)
{
    await Console.Out.WriteAsync("An error occurred while sending email: " + ex.ToString());
    return;
}

private static async Task<SendEmailResponse?> SendEmailAsync(IMailtrapClient mailtrapClient, SendEmailRequest request)
{
    ArgumentNullException.ThrowIfNull(mailtrapClient);
    ArgumentNullException.ThrowIfNull(request);

    ValidationResult validationResult = request.Validate();
    if (!validationResult.IsValid)
    {
        // Malformed email request, use validationResult to get errors
        return null;
    }

    return await mailtrapClient.Email().Send(request);
}

private static SendEmailRequest FullyFeaturedRequest()
{
    return SendEmailRequest
        .Create()
        .From("john.doe@demomailtrap.com", "John Doe")
        .ReplyTo("reply@example.com")
        .Category("Your Category")
        .To("hero.bill@galaxy.net")
        .Cc("star.lord@galaxy.net")
        .Bcc("noreply@example.com")
        .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.")
        .Html(
            @"<html>
                <body>
                    <p><br>Hey!</br>
                    Learn the best practices of building HTML emails and play with ready-to-go templates.</p>
                    <p><a href=""https://mailtrap.io/blog/build-html-email/""> Mailtrap's Guide on How to Build HTML Email</a> is live on our blog</p>
                    <img src=""cid:logo"">
                </body>
            </html>"
        )
        .Header("X-Message-Source", "domain.com") // Custom email headers (optional)
        .CustomVariable("user_id", "45982")
        .CustomVariable("batch_id", "PSJ-12")
        .Attach(
            content: Convert.ToBase64String(File.ReadAllBytes("./preview.pdf")),
            fileName: "preview.pdf",
            disposition: DispositionType.Attachment,
            mimeType: MediaTypeNames.Application.Pdf
        );
}

private static SendEmailRequest TemplateBasedRequest()
{
    return SendEmailRequest
        .Create()
        .From("example@your-domain-here.com", "Mailtrap Test")
        .ReplyTo("reply@your-domain-here.com")
        .To("example@gmail.com", "Jon")
        .Template("bfa432fd-0000-0000-0000-8493da283a69")
        .TemplateVariables(new Dictionary<string, object>
        {
            { "user_name", "Jon Bush" },
            { "next_step_link", "https://mailtrap.io/" },
            { "get_started_link", "https://mailtrap.io/" },
            { "onboarding_video_link", "some_video_link" },
            { "company", new Dictionary<string, object>
                {
                    { "name", "Best Company" },
                    { "address", "Its Address" }
                }
            },
            { "products", new object[]
                {
                    new Dictionary<string, object> { { "name", "Product 1" }, { "price", 100 } },
                    new Dictionary<string, object> { { "name", "Product 2" }, { "price", 200 } }
                }
            },
            { "isBool", true },
            { "int", 123 }
        });
}

Other examples

Email API/SMTP

  • Email Sending - Send an email (Transactional and Bulk streams), Send an email with a template and/or with attachments,
  • Batch Email Sending - Batch email sending, sending with a template and/or with attachments.

Email Sandbox (Testing)

Contacts Management

General

Configuration & Setup

Each example includes detailed comments and demonstrates best practices for error handling, configuration, and resource management.


Supported functionality

Currently, with this SDK, you can:

Email API/SMTP

  • Send an email (Transactional and Bulk streams)
  • Send an email with a template
  • Send emails with attachments
  • Send batch of emails (Transactional and Bulk streams, with template and attachments)
  • Sending domain management

Email Sandbox (Testing)

  • Send an email
  • Send an email with a template
  • Message management
  • Inbox management
  • Project management

Contacts Management

  • Contacts management
  • Fields management
  • Lists management
  • Import/Export management
  • Events management

General

  • Email Templates management
  • Account access management
  • Permissions management
  • Billing information and usage statistics
  • Domain verification

Documentation

Please visit Documentation Portal for detailed setup, configuration and usage instructions.

Contributing

We believe in the power of OSS and welcome any contributions to the library on GitHub. Please refer to Contributing Guide for details. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the code of conduct.

License

The package is available as open source under the terms of the MIT License.

Code of Conduct

Everyone interacting in the Mailtrap project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.

About

Official mailtrap.io .NET client

Resources

License

Code of conduct

Contributing

Stars

Watchers

Forks

Packages

 
 
 

Contributors 8

Languages