Send and Receive Emails in ASP.NET C#

On January 30, 2024
9min read
Piotr Malek Technical Content Writer @ Mailtrap
Sending emails in asp.net

You’ve got a long ASP.NET web development project and lots of work in Visual Studio ahead. You’re trying to wrap your head around all the tasks at hand – infrastructure, business logic, admin panel, integrations. On top of that, there’s a long list of “could have” type of features that your team would like to implement if time and resources allow.

One of the features is adding the option to use the Microsoft ASP.NET framework to send mail. And while implementing this feature is not rocket science, we strongly recommend thinking about it sooner rather than later.

To make it easier for you, we’ve created this 2024 ASP.NET C# tutorial with various code snippets you can use to enable email sending. So if you’re eager to learn more, keep on reading!

How to send emails in ASP.NET C# using SMTP server?

The first route you could take to enable email sending from your ASP.NET web application is using code that will establish a connection with an SMTP host server. 

For those unaware, an SMTP server is a server running the Simple Mail Transfer Protocol (SMTP) (the most common communication standard used in email transmission) to send, receive, and/or relay outgoing mail between senders and receivers. 

In ASP.NET, MailKit – a third-party open-source library – is used to interact with email services using various protocols such as IMAP, POP3, and SMTP, thus allowing developers to integrate email functionality into their applications.

To install MailKit in .NET, go into the Package Manager Console of Visual Studio and run the following command:

Install-Package MailKit

After a successful installation, use the code snippet below to initiate the actual email sending:

using System;

using MailKit.Net.Smtp;
using MailKit;
using MimeKit;

namespace TestClient {
  class Program
  {
    public static void Main (string[] args)
    {
      var email = new MimeMessage();

      email.From.Add(new MailboxAddress("Sender Name", "sender@email.com"));
      email.To.Add(new MailboxAddress("Receiver Name", "receiver@email.com"));

      email.Subject = "Testing out email sending";
     email.Body = new TextPart(MimeKit.Text.TextFormat.Plain) { 
    Text = "Hello all the way from the land of C#"
};
      using (var smtp = new SmtpClient())
      {
        smtp.Connect("smtp.server.address", 587, false);

        // Note: only needed if the SMTP server requires authentication
        smtp.Authenticate("smtp_username", "smtp_password");

        smtp.Send(email);
        smtp.Disconnect(true);
      }
    }
  }
}

Note: Do keep in mind that you will need to modify the code above (as well as the rest of the code from this article) to fit your specific needs, meaning that things like the email addresses used, the message content, and the SMTP server details should be replaced. 

So, for example, those of you intending to send your email using the Gmail SMTP server and your Gmail account in ASP.NET C# should put “smtp.gmail.com” instead of “smtp.server.address”.

Also, in case you are using ASP.NET Core, please refer to an ASP.NET Core-specific tutorial, as the code you need will not be the same as the one in this tutorial.

How to send emails in ASP.NET C# using an API?

The second, maybe just as popular route for sending emails in ASP.NET C#, is using an email API – a software solution that provides apps with functionalities present in email platforms such as email generation and sending, email template manipulation, analytics, domain authentication, and more, depending on the email API.

This route is quick, has an additional layer of protection thanks to utilizing API keys (unlike less secure apps), and gives you access to a range of features.

Mailtrap Email Sending is a sending solution that offers a reliable Email API and SMTP Service you can use to reach customers’ inboxes just in time.

Email Sending is a great choice for developers who want a stable working sending product along with full control over email deliverability through helicopter view dashboards, in-depth analytics, and alerts. And since Mailtrap Email Sending comes with an email delivery time of ≈ 1 sec, it will have no issues fulfilling your sending needs.

Once you decide on using the Mailtrap Email Sending or migrating to it, you are in for a smooth and secure setup.

First, you’ll need a Mailtrap account

With your account active, go to Sending Domains. 

There, you should add a sending domain you own and verify it using generated DNS records.

Once the domain is verified, go to SMTP/API Settings tab. You’ll see Transactional and Bulk Stream. Pick Transactional Stream if you’re sending non-promotional application emails and choose Bulk Stream if you’re sending promotional emails in bulk.

Under each stream, you’ll see a toggle that allows you to choose between API and SMTP services. Toggle the switch to API and you’ll see the API endpoint (Host) and your API key. An easier route is to choose C# from the dropdown menu.

Note: Each Stream has a different endpoint, make sure you choose the correct one.

Mailtrap Email Sending API integration for C Sharp

But before you copy and paste it into your ASP.NET app, remember to install https://restsharp.dev/ as an HTTP client by including the three namespaces below:

// in the beginning of the file
using RestSharp;
using System.Text.Json;
using System.Text.Json.Serialization;

Once you’ve done that, proceed with the copying and pasting.

var to = new { email = "some.nugget@gmail.com" };
var from = new { email = "mailtrap@somenugget.dev", name = "Mailtrap Test" };
var args = new {
  from = from,
  to = new[] { to },
  subject = "You are awesome",
  text = "Congrats for sending your first email with Mailtrap!",
  category = "Integration Test"
};

var client = new RestClient("https://send.api.mailtrap.io/api");
var request = new RestRequest("/send", RestSharp.Method.Post);
 
request.AddHeader("Authorization", "Bearer YOUR_TOKEN");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", 
JsonSerializer.Serialize(args), ParameterType.RequestBody);

RestResponse response = client.Execute(request);

Console.WriteLine(response.Content);

Run the code, and if everything is in order, you can start sending!

Note: Mailtrap also supports SMTP, so if you want to use it as the SMTP server of your ASP.NET application, you can do so by going to the SMTP/API Settings tab and then picking SMTP under the relevant stream. This will provide you with the credentials you need to use for sending your emails.

How to send an HTML email in ASP.NET C#?

Sending a plain text email is completely enough in a lot of cases. But, to better engage your audience and make your emails richer in content, you should send email in HTML format.

To get this done in ASP.NET C#, we will make use of the same code from the “How to send emails in ASP.NET C# using SMTP server” section of this article, with some changes implemented, of course.

The first change will be made in the part of the code where the email body is defined.

Previously, when defining the body of a plain text email, we used:

 email.Body = new TextPart(MimeKit.Text.TextFormat.Plain) { 
    Text = "Hello all the way from the land of C#"
};

If we now replace this piece of code with the one below, our email message will go from plain text format to HTML format:

var bodyBuilder = new BodyBuilder();

bodyBuilder.HtmlBody = "<p>Hey,<br>Just wanted to say hi all the way from the land of C#.<br>-- Code guy</p>";

bodyBuilder.TextBody = "Hey,
Just wanted to say hi all the way from the land of C#.
-- Code guy"; 

message.Body = bodyBuilder.ToMessageBody();

Adding images inline

After mastering HTML emails, the next thing most people want to learn about is how to add images to said emails. Lucky for you, we’ve got you covered there as well!

When trying to send an email with image in body using C# code, you’re not going to use the typical <img src=”” alt=”” />construction. This would only add the image as an attachment to the email, which is something we don’t want to do. Instead, what you want to use is the LinkedResource object to directly embed the image. 

Here is what that looks like in code:

var bodyBuilder = new BodyBuilder(); 
bodyBuilder.TextBody = @"Hey, Just wanted to say hi all the way from the land of C#. -- Code guy"; 
var image = builder.LinkedResources.Add(@"C:\Users\CodeGuy\Documents\selfie.jpg");
image.ContentId = MimeUtils.GenerateMessageId();
bodyBuilder.HtmlBody = string.Format(@"<p>Hey,<br>Just wanted to say hi all the way from the land of C#.<br>-- Code guy</p><br>
<center><img src=""cid:{0}""></center>", image.ContentId);
message.Body = bodyBuilder.ToMessageBody();

How to send emails with attachments?

Attachments, be it images or other types of documents, can also be added to your emails using C# code. And it’s quite simple!

Let’s say you want to attach a PDF document. To make that happen, we’ll use the Attachments property of the BodyBuilder class, which works with all of the following attachment types:

  • Image files (e.g., JPEG, PNG, GIF)
  • Document files (e.g., PDF, DOCX, XLSX)
  • Audio and video files (e.g., MP3, MP4)
  • Archive files (e.g., ZIP, RAR)

Below you can find the code we used to add an attachment with the filename “tutorial.pdf” using the mentioned property:

var builder = new BodyBuilder();

// Set the plain-text version of the message text
builder.TextBody = @"Hey,
  Just wanted to say hi all the way from the land of C#. Also, here's a cool PDF tutorial for you!
  -- Code guy
";

// The part where we include the new attachment...
builder.Attachments.Add(@"C:\Users\CodeGuy\Documents\tutorial.pdf");

message.Body = builder.ToMessageBody();

How to send emails to multiple recipients in ASP.NET C# using SMTP server?

If you’ve ever sent an email using an email client like Gmail, Apple Mail, Outlook, etc., then you know that you can add quite a few recipients. This holds true for emails sent using your own code as well.

Multiple recipients in ASP.NET C# can be added using the InternetAddressList class and the AddRange method by first creating an an instance of the class using an empty constructor and then adding all the recipients to it.

InternetAddressList list = new InternetAddressList();
list.Add(new MailboxAddress("First Receiver", "first@email.com"));
list.Add(new MailboxAddress("Second Receiver", "second@email.com"));
list.Add(new MailboxAddress("Third Receiver", "third@email.com"));

After that, you proceed with creating an instance of the MimeMessage class, adding the sender, and adding the list of recipients to the instance with the AddRange method. 

var message = new MimeMessage();
message.From.Add(new MailboxAddress("Sender Name", "sender@email.com"));
message.To.AddRange(RecipientList);

How to send emails in ASP.NET C# without SMTP server?

Although not so common, there are situations in which people want to send emails in ASP.NET C# without having to use an SMTP server. And while this is technically possible by doing a DNS MX lookup, it’s not recommended, and here is why:

  • Your emails might be treated as spam, especially if you send them from a dynamic IP.
  • Each recipient’s email server will need to be resolved manually.
  • Compared to other methods, querying DNS manually consumes more CPU and networking, making the performance worse.

So, what does this “scary” DNS MX lookup entail? Essentially, it finds the mail server of the domain the email address you’re trying to reach is on so you can connect to it. What this means is that you’re still going to use an SMTP server, just not yours!

In order to do a DNS MX lookup in your ASP.NET app, you’ll need to install an open source library for .NET called DnsClient.NET and use your variation of the following code:

// in the top of the file
using System.Net;
using System.Net.Mail;
// requires installation of https://www.nuget.org/packages/DnsClient
using DnsClient;

MailAddress to = new MailAddress("charles@westminster.co.uk");
MailAddress from = new MailAddress("piotr@mailtrap.com");
// The MailMessage class is a class of System.Net.Mail namespace for creating and managing email messages
MailMessage message = new MailMessage(from, to);
message.Subject = "See you Monday?";
message.Body = "Charles, I didn't hear back from you. Let me know if we're still scheduled for Monday.";

LookupClient lookup = new LookupClient();
IDnsQueryResponse response = lookup.Query("westminster.co.uk", QueryType.MX);

foreach(DnsClient.Protocol.MxRecord record in response.Answers) {
	Console.WriteLine(ObjectDumper.Dump(record.Exchange));
	SmtpClient client = new SmtpClient(record.Exchange, 25);
	try
	{
		client.Send(message);
		// if we reached this point, our email was sent, and we can break the loop
		break;
	}
	catch(SmtpException ex)
	{
		Console.WriteLine(ex.ToString());
	}
}

Another way to skip providing SMTP details is to simply use a web API, the Mailtrap Email Sending we mentioned earlier, for instance. That way, you will have a quick, hassle-free experience and prevent your emails from ending up in the spam folder, which might be the case if you go for the DNS MX lookup method.

How to test your emails before sending them?

With the email-sending functionality put in place in your ASP.NET app, it’s time to start shooting out emails, right? Well, not just yet!

Although your emails might look great to you, that doesn’t mean they will look just as great to recipients as this highly depends on the email clients they use and how they render your HTML/CSS code. This is exactly why it’s so important to do email testing before you send an email notification or a complex marketing email.

For email testing purposes, we recommend using tools such as Mailtrap Email Testing

This tool, besides being the other half of the Mailtrap Email Delivery Platform together with Email Sending, is a great solution for previewing, inspecting, and debugging emails. Think of it as a safe environment for testing emails in staging that removes the risk of you spamming users with test emails.

With Mailtrap Email Testing’s HTML Check feature, you are able to check the support popular email clients have for the HTML/CSS used in your custom emails or email templates.

You can view the results for a specific email client, device type, or all at once. Plus, you can count on detailed information for each HTML element/CSS rule, including email client support, links to code lines with errors, and notes with extra information on an error.

Mailtrap Email Testing inbox

Mailtrap Email Testing users also have access to email content spam score checking, blacklist reports, email headers information, an API, ready-to-use integrations for 20+ different languages, and more.

So how do you get started with testing in ASP.NET C# using Mailtrap Email Testing? 

With an already created Mailtrap account, log into the dashboard and go to Email Testing – > Inboxes. Then, find the SMTP Settings section, pick C# as your language of choice, and copy-paste the code provided into your ASP.NET application:

// in the top of the file
using System.Net;
using System.Net.Mail;
 
SmtpClient smtp = new SmtpClient("sandbox.smtp.mailtrap.io", 2525);  
smtp.EnableSsl = true;
smtp.Credentials = new NetworkCredential("SMTP_USERNAME", "SMTP_PASSWORD");
smtp.Send(new MailMessage("fromAddress@example.com", "toAddress@example.com", "Hello world", "testbody"));

Run the code, and if everything seems to be in order, you are free to start testing!

Note: Mailtrap Email Testing also allows you to just copy the SMTP/POP3 credentials it generates for you and paste them into your code if you prefer doing a more hands-on setup of the mail testing tool.

Summary

And there you have it! An easy tutorial on how to implement another piece of your ASP.NET application puzzle – the option to send an email with C# and ASP.NET. 

To make email sending and testing simpler, we recommend using a solution like the Mailtrap Email Delivery Platform. It has a free plan, plus it’s easy to use, so why not give it a shot?

We’d love to hear what other topics you’d like to read about on our blog? How to send confirmation email using MailKit? How to send email notification in ASP.NET MVC? Or something totally different? Let us know on Twitter!

Article by Piotr Malek Technical Content Writer @ Mailtrap