Learn to send emails in C# using SMTP with .Net framework. Include namespaces System.Net and System.Net.Mail, set up MailMessage with sender, recipient, subject, and body. Configure SmtpClient with server details, use Send() method. Covers attachments and MailKit library.

The C# language is a popular programming language among developers. If it’s not web application development, they’re busy building enterprise software or games. All these applications have users who expect some form of communication from app owners.

Email communication is one of the most effective ways to communicate with application users. That’s why these applications often need to have email-sending functionality.

That said, how do developers incorporate email-sending functionality into their applications and send emails in C#?

While there are several ways to achieve this, we are primarily going to talk about SMTP.

Keep reading!

Google SMTP – Two-Step Verification and App Passwords:

To enhance security, Google requires applications to use an app-specific password, rather than your actual password, to authenticate. To create an app password, you must first enable two-step verification on your Google account. This process can be done as follows:

  1. Visit the Google Account settings.
  2. Select “Security” from the left-hand side.
  3. Under the “Signing in to Google” section, click on “2-Step Verification” and follow the prompts to enable it.
  4. After enabling two-step verification, click on “App Passwords”. You may be asked to re-enter your password.
  5. In the App passwords section, select “Mail” in the “Select app” dropdown, and select the device you’re using in the “Select device” dropdown, then click “Generate”.
  6. Google will generate a new 16-character password for you. You will use this in your code, instead of your regular Google password.

Now, let’s move on to the actual coding.

Sending Emails in C# With SMTP?

One of the most common ways to send emails in C# applications is by using an SMTP server. However, since C# can’t interact with an SMTP server on its own, you need the .Net framework to achieve this.

In case you’re new to this, .Net is an open-source developer platform that’s used for building different types of applications – gaming, mobile, web, and many more. Not only does it support a wide range of programming languages, but it also has different types of editors and libraries.

The .Net framework is very key in the email-sending process as it contains classes for sending emails to an SMTP server which in turn delivers them to the recipients.

Before you start using .Net, make sure you have the following namespaces in your application:

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

Other prerequisites include:

  1. A valid email account with an SMTP server. That could be Gmail, Outlook, or an email-sending solution like Maileroo
  2. Have a .Net development environment installed – Visual Studio or Visual Studio Code
  3. Basic knowledge of C#/.Net programming and its applications

Next Steps

Note: First, you need to set up your project. You can either use an existing C# console application or create a new one.

dotnet new console -n SmtpTool

In addition to this, make sure you have the required NuGet packages installed to work with emails SMTP. For this purpose, go ahead and install the System.Net.Mail.

With that, you’re set to start sending an email in C#.Net using the SMTP protocol. You can use the following code to send your first email:

using System;
using System.Net;
using System.Net.Mail;
  
class Program
{
    static void Main(string[] args)
    {
        MailMessage mailMessage = new MailMessage(senderEmail, recipientEmail);
        mailMessage.From = new MailAddress("email@maileroo.com");
        mailMessage.To.Add("recipient@email.com");
        mailMessage.Subject = "Hello world";
        mailMessage.Body = "This is a test email sent using C#.Net";

        SmtpClient smtpClient = new SmtpClient(smtp.maileroo.com);
        smtpClient.Host = "smtp.maileroo.com";
        smtpClient.Port = 587;
        smtpClient.UseDefaultCredentials = false;
        smtpClient.Credentials = new NetworkCredential("SenderEmail," "SenderPassword");
        smtpClient.EnableSsl = true;

        try
        {
            smtpClient.Send(mailMessage);
            Console.WriteLine("Email Sent Successfully.");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }
    }
}

We just did a simple code up there, but you want to know how we got here. Take a look at the following steps to understand the code:

Step 1: The System.Net.Mail contains all the classes used in sending and receiving emails. On the other hand, the System.Net takes care of the network credentials. Therefore, they need to be part of your program.

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

Part 2: You need the MailMessage class object to create a message. Therefore, use it to provide details such as the sender, recipient, subject, and message body. Here’s a code example for constructing an email message:

Constructing an email message

MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress("email@maileroo.com");
mailMessage.To.Add("recipient@email.com");
mailMessage.Subject = "Subject";
mailMessage.Body = "This is a test email sent using C#.Net";

Keep in mind that the From email should be the domain from which you want to send emails. In this case, we chose maileroo.com as we are using the SMTP server details from Maileroo to send emails in C#.Net. So, replace accordingly.

Step 3: Next, use the SmtpClient to configure the SMTP details. In this case, we are using SMTP details from Maileroo. Replace the credentials with the SMTP server you’re using. 

Configuring SMTP client

SmtpClient smtpClient = new SmtpClient();
smtpClient.Host = "smtp.maileroo.com";
smtpClient.Port = 587;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential("SenderEmail", " SenderPassword");
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;

Step 4: Lastly, use the Send() of the SmtpClient class as smtpClient.Send(mailMessage); to send an email.

That’s it. Now you can send emails using SMTP protocol in C#.Net.

Sending an Email With Attachments

Add the Attachment object in the MailMessage object to send an attachment in the email. Use the code example below to achieve this:

Sending Attachment

MailMessage message = new MailMessage();
mailMessage.From = new MailAddress("email@maileroo.com");
mailMessage.To.Add("recipient@email.com");
mailMessage.Subject = "Hello world";
mailMessage.Body = "This is a test email with an attachment.";

// Create a new Attachment object
Attachment attachment = new Attachment("path_to_attachment_file.txt");

// Add the attachment to the MailMessage object
message.Attachments.Add(another_attachment.pdf);

smtpClient.Send(message);

Note: Replace the  “path_to_attachment_file.txt” and “another_attachment.pdf ” with paths to your actual attachments. 

Configuring Email Settings in the Web.Config File

Configuring email settings in web.config or app.config  allows you to separate configuration from code for easy maintenance. In the context of sending emails in C# .NET using SMTP, you can store SMTP server details, credentials, and other email-related settings in this file so that you’re able to change them without code. 

Code Example

<system.net>
    <mailSettings>
    <smtp from="email@maileroo.com">
    <network SmtpServer="smtp.maileroo.com"
                SmtpPort="587"
                SmtpUserName="your_email_address"
                SmtpPassword="your_email_password"
                enableSsl="true" />
		</smtp>
	</mailSettings>
</system.net>

Don’t forget to replace values for SmtpServer, SmtpPort, SmtpUserName, and SmtpPassword with your actual SMTP server details. 

Now that we’ve stored email settings, including server credentials, in the web.config file, you can send emails without hardcoding sender’s details directly in your C#.Net code using the following code:

MailMessage message = new MailMessage();
message.To.Add(new MailAddress("recipient@email.com"));
message.Subject = "Hello world";
message.Body = "This is a test email sent using C#.Net.";

Attachment attachment = new Attachment("path_to_attachment_file.txt");
message.Attachments.Add(attachment);
SmtpClient smtpClient = new SmtpClient();
smtp.Send(message);

Sending Emails in C# with MailKit

MailKit is a powerful open-source .Net library that facilitates both the sending and receiving of emails. We use it in place of the SmtpClient class of the System.Net.Mail namespace. It’s highly recommended for those interested in taking a modern development approach as it contains modern protocols. 

To use MailKit, first install it via NuGet. You can do this in the Package Manager Console of Visual Studio using the command:  Install-Package MailKit

As soon as you install it, use the following C# MailKit code example to send your first email. Remember to customize it as per your needs. 

using System;
using MailKit.Net.Smtp;
using MimeKit;
  
namespace TestClient {
  class Program
  {
    public static void Main (string[] args)
    {
      var email = new MimeMessage();

      email.From.Add(new MailboxAddress("SenderName", "sender@email.com"));
      email.To.Add(new MailboxAddress("RecipientName", "recipient@email.com"));

      email.Subject = "Hello world";
      email.Body = new TextPart(MimeKit.Text.TextFormat.Html) { 
        Text = "This is a test email sent using C#"
      };

      using (var smtp = new SmtpClient())
      {
        smtp.Connect("smtp.maileroo.com", 587, false);

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

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

Note: The SmtpClient class used in this code isn’t the same one as the one from the System.Net.Mail namespace but from MailKit.

MailKit Send an HTML email in .NET

This code sends a simple HTML email using the Ethereal fake SMTP service, for quick testing you can create a temporary inbox at https://ethereal.email/ and copy the SMTP configuration options. There are instructions further below on how to use a few other popular SMTP providers – Gmail, Hotmail, Office 365 and AWS SES.

// create email message
var email = new MimeMessage();
email.From.Add(MailboxAddress.Parse("from_address@example.com"));
email.To.Add(MailboxAddress.Parse("to_address@example.com"));
email.Subject = "Test Email Subject";
email.Body = new TextPart(TextFormat.Html) { Text = "<h1>Example HTML Message Body</h1>" };

// send email
using var smtp = new SmtpClient();
smtp.Connect("smtp.ethereal.email", 587, SecureSocketOptions.StartTls);
smtp.Authenticate("[USERNAME]", "[PASSWORD]");
smtp.Send(email);
smtp.Disconnect(true);

MailKit Send a plain text email in .NET

This code sends the same email as above with a plain text body.

// create email message
var email = new MimeMessage();
email.From.Add(MailboxAddress.Parse("from_address@example.com"));
email.To.Add(MailboxAddress.Parse("to_address@example.com"));
email.Subject = "Test Email Subject";
email.Body = new TextPart(TextFormat.Plain) { Text = "Example Plain Text Message Body" };

// send email
using var smtp = new SmtpClient();
smtp.Connect("smtp.ethereal.email", 587, SecureSocketOptions.StartTls);
smtp.Authenticate("[USERNAME]", "[PASSWORD]");
smtp.Send(email);
smtp.Disconnect(true);


Send SMTP email with Gmail, Hotmail, Office 365 or AWS SES

To change the above code to use a different email provider simply update the host parameter (the first parameter) passed to the smtp.Connect() method, for example:

// gmail
smtp.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTls);

// hotmail
smtp.Connect("smtp.live.com", 587, SecureSocketOptions.StartTls);

// office 365
smtp.Connect("smtp.office365.com", 587, SecureSocketOptions.StartTls);

// aws ses (simple email service)
smtp.Connect("email-smtp.[AWS REGION].amazonaws.com", 587, SecureSocketOptions.StartTls)


Wrap it up in an Email Service

To encapsulate the email sending functionality so it’s easy to send email from anywhere in your .NET app you can create an EmailService class and IEmailService interface like below.

The email service is taken from a .NET auth boilerplate API tutorial I posted recently, to test the email sending functionality you can run the API locally and register an account which triggers a verification email, for full instructions see.

namespace WebApi.Services;

using MailKit.Net.Smtp;
using MailKit.Security;
using Microsoft.Extensions.Options;
using MimeKit;
using MimeKit.Text;
using WebApi.Helpers;

public interface IEmailService
{
    void Send(string to, string subject, string html, string from = null);
}

public class EmailService : IEmailService
{
    private readonly AppSettings _appSettings;

    public EmailService(IOptions appSettings)
    {
        _appSettings = appSettings.Value;
    }

    public void Send(string to, string subject, string html, string from = null)
    {
        // create message
        var email = new MimeMessage();
        email.From.Add(MailboxAddress.Parse(from ?? _appSettings.EmailFrom));
        email.To.Add(MailboxAddress.Parse(to));
        email.Subject = subject;
        email.Body = new TextPart(TextFormat.Html) { Text = html };

        // send email
        using var smtp = new SmtpClient();
        smtp.Connect(_appSettings.SmtpHost, _appSettings.SmtpPort, SecureSocketOptions.StartTls);
        smtp.Authenticate(_appSettings.SmtpUser, _appSettings.SmtpPass);
        smtp.Send(email);
        smtp.Disconnect(true);
    }
}

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

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

var bodyBuilder = new BodyBuilder();

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

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

message.Body = bodyBuilder.ToMessageBody();

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

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

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

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

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. 

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

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

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;

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

For IMAP, the following using directives are needed. 

using System;

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

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

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

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#.

Conclusion

Sending emails in C# .NET via SMTP is a straightforward process, whether it’s with the System.Net.Mail namespace or MailKit. In this article, we covered the basics of sending a simple email and demonstrated how to add attachments to your emails. Feel free to customize the examples to meet the specific requirements of your application.

You can also view the working source for all the examples here on Github.

Leave a Reply

Your email address will not be published. Required fields are marked *