DEV Community

nataliiapolomkina
nataliiapolomkina

Posted on • Originally published at mailtrap.io

Send and Receive Emails in C#

As one of Microsoft’s most successful programming languages, it’s safe to say that C# enjoys a lot of popularity and adoption among developers.

These same developers are behind the creation of everything from desktop and web applications to enterprise software and games, which often need to have an email-sending functionality for distributing email notifications to users.

So how do developers incorporate the email-sending functionality into their software and send emails with C#? We tackle this question in the text below, so if you’re interested, keep on reading!

How to send emails in C# with SMTP?

The most common way of sending emails from your C# application is by using a Simple Mail Transfer Protocol (SMTP) server. But, as C# is not able to communicate with and instruct an SMTP host server on its own, you will need the .NET framework.

In case you are not on a first-name basis with .NET, it’s an open-source developer platform/framework also created by Microsoft. It is for building different types of applications (web, mobile, desktop, gaming, IoT, and more) and supports a range of languages, editors, and libraries.

What makes .NET so crucial in the email-sending process is the fact that it contains classes for sending emails to an SMTP server which then delivers them to recipients.

To start using .NET in your application, make sure that within it, you have the following two namespaces:

using System.Net;
using System.Net.Mail;

Then, you can use your variation of the following code example below to send your first email using C#.

Note: Although the code below can be used, it is considered somewhat outdated as it uses the SmtpClient class of the System.Net.Mail namespace instead of the MailKit library one (covered later in the article), which is more suited to modern development standards. So, if you are interested in taking only the more modern coding approach, please skip to the next section of this article.

using System;

using System.Net;
using System.Net.Mail; 

namespace TestClient {
  class Program
  {
    public static void Main (string[] args)
    {
      MailAddress to = new MailAddress("ToAddress");
      MailAddress from = new MailAddress("FromAddress");

      MailMessage email = new MailMessage(from, to);
      email.Subject = "Testing out email sending";
      email.Body = "Hello all the way from the land of C#";

      SmtpClient smtp = new SmtpClient();
      smtp.Host = "smtp.server.address";
      smtp.Port = 25;
      smtp.Credentials = new NetworkCredential("smtp_username", "smtp_password");
      smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
      smtp.EnableSsl = true;

      try
      {
        /* Send method called below is what will send off our email 
         * unless an exception is thrown.
         */ 
        smtp.Send(email);
      }
      catch (SmtpException ex)
      {
        Console.WriteLine(ex.ToString());
      }
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

If you paid close attention to the code above containing the MailMessage C# example (no worries if you didn’t; we’re not in a rush :)), you will notice the use of placeholders for things such as the from and to email addresses and, more importantly, the SMTP server details.

All of these are customized. So, for instance, if you want to send an email using Gmail SMTP server, you should replace smtp.server.address with smtp.gmail.com.

Our choice for an SMTP server falls on Mailtrap’s primarily because we enjoy how easy it is to find the necessary credentials and complete the setup.

We will talk more about Mailtrap as an email delivery platform a bit later, as it could be a great solution for both testing and sending your emails. But, for the time being, it’s great to keep in mind the practicality of its SMTP server for when it comes time to decide on one yourself. At the end of the day, it’s not the most practical to send email without SMTP server.

How to send emails in C# with MailKit?

MailKit is a cross-platform .NET mail-client library facilitating not only email sending but receiving as well.

Now, you might be thinking, “Wait, wait. Didn’t you just showcase how the email-sending process is done with no involvement of MailKit?” Yes, we did. And while the code above is valid and should work without an issue in most cases, the SmtpClient class used in it might cause a few hiccups.

Why? Well, according to Microsoft and their documentation, the SmtpClient class lacks support for many modern protocols and is thus not recommended for new development. Instead, the use of MailKit or a different email library and its classes is a better alternative.

To start using MailKit, you will first need to install it via NuGet.

This is done in the Package Manager Console of Visual Studio using the following command:

Install-Package MailKit

After the installation, you can start sending emails using this C# MailKit example code with customizations, of course:

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.Html) { 
        Text = "<b>Hello all the way from the land of C#</b>"
      };

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

Enter fullscreen mode Exit fullscreen mode

Yes, yes, we know what you spotted in the code, the SmtpClient class. No worries, this isn’t the same class from the System.Net.Mail namespace.

This is the SmtpClient class from MailKit.Net.Smtp, which is the Microsoft-approved alternative.

How to send emails in C# with Mailtrap Email API?

What you saw demonstrated above was the old-fashioned way of sending emails in C#. And while there is nothing wrong with it, it certainly isn’t as advanced and effortless as sending with third-party email services, which more often than not, provide automation features, analytics, and more.

When it comes to picking these types of services, you might want to consider Mailtrap Email API – the email-sending side of the Mailtrap email delivery platform and the optimal choice for those who want to have more control over their email deliverability.

After going through the secure and smooth setup, you can use Email API to send your emails and make them land in people’s inboxes instead of their spam folders.

Email API makes this possible by giving you tools to spot and fix early sending issues.

To be more specific, those who decide on using Email API as their third-party email service gain access to actionable analytics features, which include daily and weekly deliverability alerts, up to 60-day email logs, webhooks, and dashboards with critical alerts.

Among the listed features, what might be the most interesting are the color-coded critical alert dashboards which can be filtered by top mailbox providers, thus enabling you to dig deeper to improve your email performance.

send email in c# 1

Speed-wise, Email API can go up to ~10000 emails/second. And to make sure email sending goes as smoothly as possible, there are dedicated IPs, auto IP warmup, and suppression lists at your disposal.

To integrate Email API into your C# application, you will need a Mailtrap account (free plan available).

Once your account is active, the next step you need to complete is adding and verifying your domain – a process described in the video below.

Upon domain verification, you should be taken to the API and SMTP Integration page, where you can find the Email API integration code containing your API key and the other necessary details in a number of programming languages, including C#.

var client = new RestClient("https://send.api.mailtrap.io/api/send");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <YOUR_API_TOKEN>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\"from\":{\"email\":\"mailtrap@mailtrap.io\",\"name\":\"Mailtrap Test\"},\"to\":[{\"email\":\"ToMailAddress\"}],\"subject\":\"You are awesome!\",\"text\":\"Congrats for sending test email with Mailtrap!\",\"category\":\"Integration Test\"}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

Enter fullscreen mode Exit fullscreen mode

As Mailtrap also supports SMTP, you can simply take the credentials provided to you and use them in your project, app, or email-sending service to start sending with Email API.

How to send an HTML email in C#?

As HTML emails are far more eye-catching than plain text, sending them serves as a simple way to better engage your recipients, and now we’ll demonstrate how it’s done in C#.

Do keep in mind that we are going to stick with the MailKit route, as there is no reason not to follow Microsoft’s advice when it comes to their own framework.

So, to create an HTML email in C#, we will use the same code that was used in the “How to send emails in C# with MailKit” section of this article but with a few tweaks.

The most notable tweak will be at the part where we define the email message body.

For a plain text email, this is the message body code:

message.Body = new TextPart("plain")
{
  Text = @"Hey, Just wanted to say hi all the way from the land of C#. -- Code guy"
};

Enter fullscreen mode Exit fullscreen mode

To now turn this message body into HTML, we’ll use the following code:

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();

Enter fullscreen mode Exit fullscreen mode

Embedding an image

If you are thinking, “but what about images,” no worries, we’ve got you covered there as well and will now demonstrate how to send email with image in body.

Embedding an image into your custom HTML email body or HTML email template requires just a few additional lines of code, and it’s nothing more complicated than what we’ve done so far:

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();

Enter fullscreen mode Exit fullscreen mode

In the code above, we used the LinkedResources property, which enables us to add a special type of attachment that is linked to from the HtmlBody property. In our case, that attachment is an image named selfie.jpg.

How to send email with attachment in C #?

While we are on the topic of attachments, let’s explain the simplest method of creating an email containing one in C#.

When using MailKit, that method involves the BodyBuilder class, which came in very handy in the creation of our HTML email.

In the code below, you can see how we added a PDF document named tutorial.pdf using the Attachments property of the BodyBuilder class:

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();

Enter fullscreen mode Exit fullscreen mode

How to send email to multiple recipients in C#?

Sending your email to multiple recipients in C# is pretty easy and involves the use of the InternetAddressList class and the AddRange method.

First, you will create an instance of the InternetAddressList class using an empty constructor, to which you then need to add all the recipients.

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

Enter fullscreen mode Exit fullscreen mode

Next, you can move on to creating the MimeMessage class instance, 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);

Enter fullscreen mode Exit fullscreen mode

Testing emails before sending them in C#: Why and how?
Sending is enabled in your C# app. Hooray! But don’t let this excitement rush you into sending emails to real recipients just yet.

Before proceeding with that, it’s essential you do some testing, and there are a couple of reasons why:

  • Your custom email or email template HTML/CSS might not look as good in other email clients as it does in yours.
  • Your email content might be a bit spammy.
  • The domain you intend on sending from might be present on blacklists.

These and other issues related to your emails can only be detected through adequate inspecting and debugging using equipped email testing tools.

Email Sandbox is the email testing side of the Mailtrap email delivery platform.

Email Sandbox is a tool geared toward devs, but it can also be used by anyone wanting to debug and inspect emails at staging. And since it comes with no risk of spamming real users during the process, unlike the manual route, it can also be considered a safe environment for email testing.

Email Sandbox has plenty of other benefits when compared to manual testing, such as the preservation of domain reputation due to using a virtual inbox as opposed to your personal one, automation of test flows and scenarios, and saving time during setup and usage.

Users of Email Sandbox have a range of features at their disposal, such as HTML/CSS analysis, email content spam score checking and previews, blacklist reports, insights into valuable tech info, and more available to them after integrating the testing tool into their C# app using a code snippet or the credentials of their virtual inbox.

send email with c sharp 2

For C# apps, the following code snippet is used:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = new SmtpClient("smtp.mailtrap.io", 2525)
            {
                Credentials = new NetworkCredential("username", "password"),
                EnableSsl = true
            };
            client.Send("from@example.com", "to@example.com", "Hello world", "testbody");
            Console.WriteLine("Sent");
            Console.ReadLine();
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Once you run the code, you can check your virtual inbox.

Your first test email should be there, and you are now able to inspect and debug it using Email Sandbox’s features.

send emails c# tutorial 3

How to receive emails in C#?

Although it’s not super common, you might need to enable your C# app to receive/retrieve emails from a POP3 or IMAP mail server. Luckily, MailKit is capable of doing exactly that.

Those of you looking to retrieve messages from a POP3 server should first make sure that you have the appropriate using directives at the top of your code file.

using System;
using MailKit.Net.Pop3;
using MailKit;
using MimeKit;

Enter fullscreen mode Exit fullscreen mode

Then, you can use the following code snippet to connect to the server and get all the messages present on it using a for or foreach loop, whatever you prefer.

using (var client = new Pop3Client())
{
    client.Connect("pop.server.com", 110, false);
    client.Authenticate("pop_username", "pop_password");

    for (int i = 0; i < client.Count; i++)
     {
        var message = client.GetMessage(i);
        Console.WriteLine("Subject: {0}", message.Subject);
    }

    client.Disconnect(true);
}

Enter fullscreen mode Exit fullscreen mode

For IMAP, the following using directives are needed.

using System;

using MailKit.Net.Imap;
using MailKit.Search;
using MailKit;
using MimeKit;

Enter fullscreen mode Exit fullscreen mode

And the code for retrieving the messages from the IMAP server will be quite similar to the one used for POP3, just with a few differences here and there.

using (var client = new ImapClient())
{
    client.Connect("imap.server.com", 993, true);
    client.Authenticate("imap_username", "imap_password");

  var inbox = client.Inbox;
    inbox.Open(FolderAccess.ReadOnly);

    Console.WriteLine("Total messages: {0}", inbox.Count);
    Console.WriteLine("Recent messages: {0}", inbox.Recent);

    for (int i = 0; i < inbox.Count; i++)
  {
        var message = inbox.GetMessage(i);
        Console.WriteLine("Subject: {0}", message.Subject);
    }

    client.Disconnect(true);
}
Enter fullscreen mode Exit fullscreen mode

As MailKit provides numerous options when it comes to messages on IMAP servers, we suggest you take a look at the available GitHub documentation.

Wrapping things up

So, that was all we had to cover in this sending with C# tutorial. From the old-fashioned method involving System.Net.Mail’s SmtpClient class which is not really recommended anymore to using MailKit and Mailtrap’s Email API which is now standard practice, we covered all the options for sending emails that might come in handy.

We also touched upon HTML emails, attachments, images, multiple recipients, and even how to retrieve emails with C# code. That being said, feel free to use this article as a handbook on all things regarding how to send email with C#.

Also, make sure to remember to never send emails without doing proper testing beforehand with tools such as Mailtrap Email Sandbox; otherwise, the spam folder might be the only place your emails reach regardless of how much time you spent tweaking the text or configuring your mail settings.

Interested in more C# content? Then you might want to check out our (ASP DotNet) ASP.NET send email and C# email validation articles. Or you can come back to our blog in a few weeks to read our soon-to-be-published sending with ASP.NET Core article.

Thanks for reading!


I hope you enjoyed our guide on sending emails in C Sharp, which was initially published in the Mailtrap blog.

Top comments (1)

Collapse
 
zakwillis profile image
zakwillis

Wow. You certainly like emails.

I wrote an email encryption/reporting application for my company (Info Rhino -Communication Manager) so I can manage and respond to emails periodically, rather than react to every email on demand. I used Mail Kit.

In theory we can bulk send emails using async looping.