Send Email in ASP.NET Core using MailKit with Attachments

Send Email c mailkit MailKit

Today in this article, we will see how to use MailKit a C# .NET library.

We will send emails in ASP.NET Core using MailKit. We will use ASP.NET .NET 6 application examples.

We shall also see how to send an email using attachments i.e. we will attach files like PDF or HTML or Images or Word doc files etc as attachments to emails we are sending to our users.


We will cover the below aspects in today’s article,

What is MailKit

MailKit is a powerful open-source library for .NET that allows developers to easily send, receive, and manipulate email messages.

MailKit provides extensive support for email protocols like SMTP, POP3, and IMAP, making it a comprehensive solution for email communication.

It is commonly used in .NET Core applications for email-related functionalities.

It supports most of the modern protocols and is also optimized for mobile devices

I was looking to build send email functionality as a Service using C# .NET Core 3.1 recently using MailKit.

The service’s core functionality was to send emails using the registered SMTP server.

As per Microsoft Send emails using SmtpClient is good for one-off emails from tools but doesn’t scale to modern requirements of the protocol.

It’s recommended to use MailKit or MimeKit or other libraries for any scaled and additional protocol requirements.

So if the requirement is simple enough to send an email SmtpClient approach will still work for you.

I found that .NET Core has full support for email functionality using MailKit.

Let’s send an email from the Gmail mail server (smtp.gmail.com) to another domain (infoATthecodebuzz.com) for this article.

I have used my own Gmail for sending an email and testing purposes which worked very well after some initial travail.

MailkIt gives RFC-compliant SMTP, POP3, and IMAP client implementations.

Getting Started

Create ASP.NET Core 3.1 or .NET 6.0 API

embed image in emailMailKit with Attachments

Please add below Nuget packages to the project,

PM> Install-Package MailKit -Version <version>

Note– Please use the latest available version.

We shall be using the POST method for sending out an email.

Please add the below namespace to your file,

using MailKit.Net.Smtp;


using MimeKit;

Let’s write the below code for the POST method.

Send Email in ASP.NET Core using MailKit – Define MimeMessage structure

As a first step please define the MimeMessage structure.

A message structure consists of header fields and a body. The body of the message can be plain text or a tree of MIME entities.

var message = new MimeMessage();
                message.From.Add(new MailboxAddress("TheCodeBuzz", "[email protected]"));
                message.To.Add(new MailboxAddress("TheCodeBuzz", "infoATthecodebuzz.com"));
                message.Subject = "My First Email";
                message.Body = new TextPart("plain")
                {
                    Text = emailData
                };

Define SMTP C# MailKit Client

Let’s now define the SMTP MailKit client.

We shall pass the MimeMessage object to the Send() API as below,

using (var client = new MailKit.Net.Smtp.SmtpClient())
          {
                       client.Connect("smtp.gmail.com", 587, false);
                        //SMTP server authentication if needed
                        client.Authenticate("[email protected]", "xxxxx");
                        client.Send(message);
                        client.Disconnect(true);
                       
          }

Above GMAIL SMTP using 587 as a standards port for the communication.

Complete the POC example demonstrating the usage as below.

You can very much use the below code in any module as suitable to your layered code structure.

Example

        [HttpPost]
        public ActionResult<IEnumerable<bool>> 
        SendEmail([FromBody] string emailData)
        {
            try
            {
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress("TheCodeBuzz", "[email protected]"));
                message.To.Add(new MailboxAddress("TheCodeBuzz", "infoATthecodebuzz.com"));
                message.Subject = "My First Email";
                message.Body = new TextPart("plain")
                {
                    Text = emailData
                };
                
                    using (var client = new MailKit.Net.Smtp.SmtpClient())
                    {
                        client.Connect("smtp.gmail.com", 587, false);
                        //SMTP server authentication if needed
                        client.Authenticate("[email protected]", "xxxxx");
                        client.Send(message);
                        client.Disconnect(true);
                    }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return StatusCode(500, "Error occured");
            }
            return Ok(true);
        }

Send Email with Attachment (HTML or . JPEG or . PDF files)

We often need to send an email with custom attachments like PDF, HTML, Images, or Excel files along with custom text bodies.

Using MimeKit.BodyBuilder

BodyBuilder from MimeKit is a helper class for building common MIME body structures and provides you the flexibility to build message structures…

Please see below how to use the BodyBuilder class.

Sending multiple Attachments using MailKit

MimeKit.BodyBuilder lets you send multiple attachments in email. Please update the above message.

The body which is defined for text only as below for both text and attachments like pdf and jpeg as shown below,

send email NET c with attachment

Using Gmail SMTP server with MailKit

For the Gmail SMTP server, the above code worked perfectly for me except I had to update a few security settings as mentioned below.

Initially, you might get the below error,

 The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. “

Gmail by default prevents you from accessing your e-mail account from external applications.

But you can update your security settings to accept the login from the application.

I got an email from Gmail saying “Critical security alert for your linked Google Account”.

  • I had to enable “Allow less secure apps: ON” to make the send email API work properly.
send email net core

Such errors are more due to the policy configured on the SMTP email server.

Make sure you are following the proper settings and policies required for a secure connection to connect to the SMTP server.

Finally, an email popped up successfully in my other domain mail Inbox from my Gmail ID.

Send Email in ASPNET Core using MailKit email net core 5 MailKit

Retrieving Messages (via Pop3)

Apart from sending emails MaiKit library also provides support for retrieving messages from pop3 servers.

Retrieving Messages (via IMAP )

MailKit library also provides full support for retrieving messages from IMAP servers.

Other Advantages of MailKit

  • Wide Email Protocol Support: MailKit provides support for multiple email protocols, including SMTP (for sending emails), POP3 (for receiving emails), and IMAP (for more advanced email operations like folder management and searching).

  • Open-Source and Cross-Platform: MailKit is an open-source library, available under the MIT License, making it freely accessible to developers.

  • High Performance and Efficient: MailKit is designed to be high-performance and efficient, optimized for handling large volumes of email messages. It utilizes asynchronous programming patterns (async/await) to avoid blocking threads and ensure responsiveness in applications.

  • Extensive MIME Support: MailKit provides extensive support for MIME (Multipurpose Internet Mail Extensions) and allows developers to work with multipart emails, attachments, inline images, and other MIME-related functionalities.

  • Secured Email Communication: MailKit supports secure communication using SSL/TLS protocols, enabling secure connections to email servers and protecting email communication from eavesdropping or interception.

MailKit is designed to be high-performance and efficient, optimized for handling large volumes of email messages.

It utilizes asynchronous programming patterns (async/await) to avoid blocking threads and ensure responsiveness in applications.

Differences between SMTP Vs MailKit

Please here to understand the high-level differences between SMTP Vs MailKit

Other references :

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!

Summary

Today in this article we learned how to send an email message using MailKit a .NET open-source library. We understand traditional SMTPClient is now obsolete and it’s recommended to use MailKit or MimeKit for scaled and additional protocol requirements.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.