Stand with Ukraine 🇺🇦 Donate to support

Send and Receive Emails in ASP.NET C#

On October 18, 2022
10min read
Piotr Malek Technical Content Writer @ Mailtrap

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 ASP.NET to send email. 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 late 2022 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. 

And while this route is a very common one, it does have some prerequisites we’ll explain in step 1 before proceeding to step 2, which entails the server configuration and the actual email sending.

Step 1 – Learn MailMessage basics

When creating an email message in ASP.NET with C#, the use of the MailMessage class belonging to the System.Net.Mail namespace is required. 

This class represents, you guessed it, an email that is sent to an SMTP server for delivery using the SmtpClient class.

When initializing an object of the MailMessage class, you can specify the sender, recipient, subject, and email body as parameters.

Using the properties of a MailMessage object, you can specify the primary email headers and elements.
More detailed information about this class’ constructors, methods, and properties can be found in Microsoft’s documentation.

Step 2 – Connect to an SMTP server and send off the message

With MailMessage basics learned, you can now write or at least understand the code necessary to establish a connection to an SMTP server and send mail.

To make things a tad more interesting, let’s imagine that your mail is intended for none other than the new U.K. monarch, King Charles.

To email ID: charles@westminster.co.uk

From email ID: piotr@mailtrap.io

Title: Good morning, Charles

Body: Charles, Long time no talk. Would you be up for lunch in Soho on Monday? I’m paying.

In order to now send an email with these details, we’ll use the aforementioned MailMessage class from the .NET framework.

// in the beginning of the file
using System.Net;
using System.Net.Mail;
MailAddress to = new MailAddress("charles@westminster.co.uk");
MailAddress from = new MailAddress("piotr@mailtrap.io");
MailMessage message = new MailMessage(from, to);
message.Subject = "Good morning, Charles";
message.Body = "Charles, Long time no talk. Would you be up for lunch in Soho on Monday? I'm paying.;";
SmtpClient client = new SmtpClient("smtp.server.address", 2525)
{
    Credentials = new NetworkCredential("smtp_username", "smtp_password"),
    EnableSsl = true
// specify whether your host accepts SSL connections
};
// code in brackets above needed if authentication required
try
{
  client.Send(message);
}
catch (SmtpException ex)
{
  Console.WriteLine(ex.ToString());
}

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 API is an API solution that will send your emails and also help you ensure those emails get delivered to the right inboxes. How? 

Well, you see, Mailtrap Email API comes with a batch of features providing actionable analytics. Within the batch, you can find timely deliverability alerts, weekly deliverability reports, 60-day email logs, dashboards with critical metrics, and more, all intended to let you gain more control over your email deliverability and spot sending issues early.

Once you decide on using the Email API or migrating to it, you are in for a straightforward process.

First, you’ll need a Mailtrap account

With your account active and access to the Mailtrap dashboard, go to Email API -> Sending Domains. 

There, you should add your domain and verify it, after which you can go to API and SMTP Integration, pick C# as your language of choice, and copy-paste the code snippet you are provided with into your ASP.NET app.

This example requires you to install https://restsharp.dev/ as an HTTP client.

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

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 a test 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 application or email sending provider, you can do so by again going to API and SMTP Integration and then picking SMTP. This should 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.

In ASP.NET C#, you can create an HTML email using the AlternateViews property. This property enables you to create copies of an email message in different formats, and here is what it looks like when used in code:

// in the beginning of the file
using System.Net;
using System.Net.Mail;
using System.Net.Mime;

SmtpClient smtp = new SmtpClient("smtp.mailtrap.io", 2525);  
smtp.EnableSsl = true;
smtp.Credentials = new NetworkCredential("SMTP_USERNAME", "SMTP_PASSWORD"); 

String from = "your@sender.email";
String to = "your@recipient.email";
String subject = "Pics from the royal wedding";
String messageBody = "Charles, sending you a quick sneak peek of the pictures" +
"we took at the last royal wedding. ";
MailMessage message = new MailMessage(from, to, subject, messageBody);

AlternateView htmlView = AlternateView.CreateAlternateViewFromString(
  $"{messageBody} <br> <img src=\"cid:Wedding\">",
  null,
  "text/html"
);

LinkedResource LinkedImage = new LinkedResource("./bestpictureever.jpeg");
LinkedImage.ContentId = "Wedding";
            
htmlView.LinkedResources.Add(LinkedImage);
message.AlternateViews.Add(htmlView);
            
try
{
  smtp.Send(message);
}
catch (SmtpException ex)
{
  return ex.ToString();
}

Adding images inline

If you look closely at the code above, you will notice that we have included an image in our email. And no, we didn’t just add it as an attachment. We created an email with image in body.

Here is how to do this yourself!

When trying to send an email with an image using C# code, you’re not going to use the typical <img src="" alt="" /> construction. This would add the image as an attachment to the email. Instead, we’ll use the LinkedResource object to directly embed the image. 

String imagePath = "bestpictureever.png";
LinkedResource LinkedImage = new LinkedResource(@imagePath);
LinkedImage.ContentId = "Wedding";

Do remember to upload the image file to your current working directory and give it a recognizable file name beforehand. 

How to send emails with attachments?

We mentioned attachments in the previous section of this article, so it’s only fair to cover how to send them along with your emails in ASP.NET C#.

Now, let’s imagine you want to send an invoice for the last royal wedding or a set of pictures as an attachment in your email to King Charles. To make that happen, you should use the Attachment class from the .NET framework on top of the MailMessage class. But, before you start again, make sure you add the attachment to your current working directory first.


// in the beginning of the file
using System.Net;
using System.Net.Mail;
using System.Net.Mime;

SmtpClient smtp = new SmtpClient("smtp.mailtrap.io", 2525);  
smtp.EnableSsl = true;
smtp.Credentials = new NetworkCredential("SMTP_USERNAME", "SMTP_PASSWORD"); 
          
String from = "your@sender.email";
String to = "your@recipient.email";
String subject = "Regarding our meeting";
String body = "Charles, as requested, sending you the invoice for Harry and Meghan's wedding. Any questions? Let me know.;";
          MailMessage message = new MailMessage(from, to, subject, body);
          
String filePath = "wedding_invoice.pdf";
Attachment attachment = new Attachment(filePath, MediaTypeNames.Application.Octet);
          
message.Attachments.Add(attachment);
 
try
{
  smtp.Send(message);
}
catch (SmtpException ex)
{
  Console.WriteLine(ex.ToString());  
}

If you need to send multiple attachments, simply use a loop and add the other files to the email. Easy, right?

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

In case King Charles is not the only person who needs to see your email, you will need to add a few more people to the list of recipients.

This is not complicated at all, and new recipients are simply added to the code, separated by a comma:

// in the beginning of the file
using System.Net;
using System.Net.Mail;

SmtpClient smtp = new SmtpClient("smtp.mailtrap.io", 2525);  
smtp.EnableSsl = true;
smtp.Credentials = new NetworkCredential("SMTP_USERNAME", "SMTP_PASSWORD"); 

MailAddress to = new MailAddress("charles@westminster.co.uk, harry@westminster.co.uk");
MailAddress from = new MailAddress("piotr@mailtrap.io");
MailMessage message = new MailMessage(from, to);
message.Subject = "Good morning";
message.Body = "Charles, Harry, There are a few unpaid invoices for the Royal Wedding. Let's talk this over on Monday.;";

try
{
  smtp.Send(message);
}
catch (SmtpException ex)
{
  Console.WriteLine(ex.ToString());
}

You can also have an email with multiple bcc and cc recipients, but that will require a few additional lines of code:

// in the beginning of the file
using System.Net;
using System.Net.Mail;

SmtpClient smtp = new SmtpClient("smtp.mailtrap.io", 2525);  
smtp.EnableSsl = true;
smtp.Credentials = new NetworkCredential("SMTP_USERNAME", "SMTP_PASSWORD"); 

MailAddress to = new MailAddress("charles@westminster.co.uk, harry@westminster.co.uk");
MailAddress from = new MailAddress("piotr@mailtrap.io");
MailMessage message = new MailMessage(from, to);
message.Subject = "Good morning";
message.Body = "Charles, Harry, There are a few unpaid invoices for the Royal Wedding. Let's talk this over on Monday.;";
message.CC.Add(new MailAddress("meghan@westminster.co.uk"));
message.Bcc.Add(new MailAddress("william@westminster.co.uk"));

try
{
  smtp.Send(message);
}
catch (SmtpException ex)
{
  Console.WriteLine(ex.ToString());
}

For the SMTP server, we put smtp.server.address just as a placeholder. If you want an easy-to-use solution for this then feel free to go with Mailtrap’s SMTP service,  since getting the credentials is very easy and the setup is hassle-free. 

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");
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 API 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 Sandbox

This tool, besides being the other half of the Mailtrap Email Delivery Platform together with Email API, 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 Email Sandbox’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.

Email Sandbox 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 Email Sandbox? 

With an already created Mailtrap account, log into the dashboard and go to Sandbox – > 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("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 Sandbox 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