How to Send Emails in C# .NET via SMTP

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.

How to Send Emails in C# .NET via SMTP
Photo by Blake Connally / Unsplash

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!

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

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.