Send email with CSharp using SMTP Client and MailSlurp

Create an SMTP client in CSharp and access MailSlurp inboxes for testing and receiving emails using the built-in `System.Net.Mail` package.

  • Table of contents

You can use CSharp's built in SMTP client package System.Net.Mail. Let us use XUnit and the MailSlurp client to create an email address and send emails to it.

How does it work?

First add the package to your CSharp project

dotnet add package mailslurp
dotnet restore

Configure your MailSlurp API Key with the email client:

using mailslurp.Api;
using mailslurp.Client;
using mailslurp.Model;

var config = new Configuration();
config.ApiKey.Add("x-api-key", "your_api_key_here");

Then you can create inboxes during tests or in your application to connect to SMTP:

var apiInstance = new InboxControllerApi(config);
var inbox = apiInstance.CreateInbox();

Assert.NotNull(inbox);
Assert.Contains("@mailslurp.com", inbox.EmailAddress);

Example XUnit tests

Using XUnit you can connect to SMTP mailboxes during tests and send and receive emails.

using System;
using System.Net;
using System.Net.Mail;
using mailslurp.Api;
using mailslurp.Client;
using mailslurp.Model;
using Xunit;

namespace SmtpService.Tests
{
    public class UnitTest1
    {
        [Fact]
        public void CanSendEmailWithMailSlurpSmtp()
        {
            var apiKey = Environment.GetEnvironmentVariable("API_KEY")
                         ?? throw new ArgumentNullException("Missing API_KEY environment variable containing MailSlurp key");

            // configure client
            var config = new Configuration();
            config.ApiKey.Add("x-api-key", apiKey);
            var inboxController = new InboxControllerApi(config);

            // create an smtp inbox
            var inbox = inboxController.CreateInboxWithOptions(new CreateInboxDto(
                inboxType: CreateInboxDto.InboxTypeEnum.SMTPINBOX
            ));
            Assert.Contains("@mailslurp.mx", inbox.EmailAddress);

            // get smtp host, port, password, username etc
            var imapSmtpAccessDetails = inboxController.GetImapSmtpAccess();
            var smtpClient = new SmtpClient(imapSmtpAccessDetails.SmtpServerHost)
            {
                Port = imapSmtpAccessDetails.SmtpServerPort,
                Credentials = new NetworkCredential(userName: imapSmtpAccessDetails.SmtpUsername, password: imapSmtpAccessDetails.SmtpPassword),
                // disable ssl recommended
                EnableSsl = false
            };
            Assert
            
            // send email to inbox
            smtpClient.Send(from: "test@external.com", recipients: inbox.EmailAddress, subject: "This inbound", body: "Hello");
            
            // wait for email to arrive
            var waitController = new WaitForControllerApi(config);
            waitController.WaitForLatestEmail(inboxId: inbox.Id, timeout: 30_000);
        }
    }
}

Other use cases

You can use System.Net.Mail to send emails in DotNET but what if you want to receive emails instead? Use MailSlurps email webhooks to have emails sent directly to your server.

webhooks

Receive emails by polling

You can use the waitFor methods with the MailSlurp SDK client. You can receive emails using waitFor methods on the WaitForControllerApi class.

var Timeout = 30000L; // max milliseconds to wait
var UnreadOnly = true; // only count unread emails

var waitForInstance = new WaitForControllerApi(config);
var email = waitForInstance.WaitForLatestEmail(inbox.Id, Timeout, UnreadOnly);

Assert.NotNull(email);
Assert.Equal("Hello", email.Subject);
Assert.Contains("Your code is: ", email.Body);
You can extract content from email bodies using RegExps:


// imagine that email body is `Your code is: 123` and you want to get the number
var rx = new Regex(@"Your code is: ([0-9]{3})", RegexOptions.Compiled);
var match = rx.Match(email.Body);
var code = match.Groups[1].Value;

Assert.Equal("123", code);

A common use case for temporary SMTP mailboxes in Csharp is verifying OTP 2FA login during integration testing. OTP one-time passwords are ephemeral codes that can be sent to a user's email address when they want to access a web application or mobile app.

See the OTP testing guide for more information.

cypress js