CSharp Email Tutorial

SMTP mailserver testing and usage in CSharp using

CSharp is a powerful language with many features. The inbuilt SMTP pacakges under System.Net.Mail offer easy email functionality. In this post we will discuss how to send and receive email in C# and .NET core using SMTP and SDK clients.

xunit

Email sending in code

To send CSharp emails use the System.Net.Mail package that is included with the .NET runtime. Here is an example using XUnit to send en email from a MailSlurp SMTP server using PLAIN authentication.

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 UnitTest0
    {
        [Fact]
        public void CanSendWithSMTP()
        {
            var smtpClient = new SmtpClient("your.smtp.host")
            {
                Port = 2525,
            };
            
            // send email to mailbox 
            smtpClient.Send(from: "test@external.com", recipients: "receiver@gmail.com", subject: "This inbound", body: "Hello");
        }
    }
}

Configure SMTP authentication

For some SMTP Mailservers such as those provided by MailSlurp you will need to use an authentication method.

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

Read email in CSharp

SMTP protocols are typically used for delivery of email messages. If you wish to read emails in CSharp applications you have a few options:

  • Run an SMTP server for inbound emails and take custom actions in response
  • Use an IMAP package to fetch messages
  • Use an email SDK like MailSlurp to send and receive

Install MailSlurp Csharp email SDK

MailSlurp is a Csharp email API service that provides free disposable email accounts (or permanent custom domains) for sending and receiving emails in CSharp applications. Create a free account to obtain an API KEY and then install the open source NuGetPackage:

dotnet-add

Configure email client

You can configure MailSlurp to receive emails in code as follows:

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

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

// create an inbox controller to control inboxes
var apiInstance = new InboxControllerApi(config);

// fetch emails
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);

More options

Related content

CSharp Email API and SMTP library

Receive email in DotNET Core using C# and MailSlurp

Java email library for SMTP and creating email addresses

MailSlurp Java SDK for sending and receive email and attachments on the JVM.

Email for testing

Test email accounts for email testing. Alternatives to Mailinator, MailTrap, Mailosaur and more.

The Most Advanced Guide on Azure Email Sending.

The Most Advanced Guide on Azure Email Sending.

Email marketing campaign bulk email testing

Send bulk transactional emails with MailSlurp online or in code using CSharp, Node.js, Java, PHP and more.

Cold Emailing in Compliance with CAN-SPAM

How to maintain a strong sender reputation and delivery when cold emailing

How to fix the any package by glob error in dotnet

Fix .NET installation on Linux for missing dotnet dependencies.

Disposable email accounts for DotNET core 6

Create real throw-away email addresses for testing and development in .NET core. Follow this guide to get started.

Do's and Don'ts for multiple SPF records

Do's and Don'ts for multiple SPF records

DotNET Core Cake Task Runner (CSharp Makefiles for coverlet code coverage and more)

Create cross platform build scripts for DotNET Core in a way similar to Makefiles.

Create a new .NET MVC project starter (with the CLI)

DotNet starter project MVC generation using the command line interface.

Email Over Blockchain

Can emails be sent over blockchain? Well kind of! LedgerMail and other and at the cutting edge of decentralized email.

Explaining Cloud Email with Options to Think About

Explaining Cloud Email with Options to Think About

GraphQL Email API Tutorial

Did you know you can send and receive emails using GraphQL?

How to choose the right email design size (for various campaigns)

Email sizes can be instrumental to determine if your consumer will comprehend and engage with your content. While the template width (600 px) is typical, there are nuances to be mindful of. There are no hard and fast standards for email template height like design blocks.

HTML Mailto Links Explained

HTML Mailto is uncomplicated to use. This link opens the default email client and adds a new notification maker. Pre-populated fields save time and prevent email bounces. This post will cover customizing mailto. We'll also discuss its viability in this decade. Come on.

How to send emails in Javascript (NodeJS)

JS SMTP email sending guide using HTML and NodeJS.

Mailinator alternative

Alternatives to Mailinator for test email accounts. Create real email addresses using MailSlurp

How to use Mailto links

Mailto links not working guide.

Manage Email Throttling Correctly!

Manage Email Throttling Correctly!

Maximum Email Size and How to Optimize It

Email sizes are fundamental for a few important reasons. One is security, and another is the performance of your email.

How to send an email using Powershell (Windows and cross-platform)

Use Send-MailMessage in Windows Powershell to send emails using an SMTP server or MailSlurp's free email API.

Transactional Email Services Compared

Sending emails is important for many applications. Top 10 transactional email services compared.

What is DKIM Email

How to setup and configure DKIM signatures with the sender policy framework (SPF)

Specflow user sign-up testing with MailSlurp accounts

How to test .NET authentication and sign-up using real email accounts with MailSlurp and SpecFlow.

.NET Selenium C#

Send and receive email in DotNET Nunit tests using Selenium and MailSlurp.

CSharp Email Tutorial

SMTP mailserver testing and usage in CSharp using

Send email with CSharp using SMTP Client and MailSlurp

Create a custom SMTP client and access MailSlurp inboxes from CSharp/DotNET.

How to send emails in VBA

Send email in Visual basic

CSharp send SMTP email

How to use CSharp SMTP client to send email with MailSlurp mail server

Email internationalization and i18n localization

Email internationalization and i18n localization

Ready to dive in?Start building email applications today.