Sending Emails in ASP.NET Core

On March 09, 2023
14min read
Dzenana Kajtaz Technical Content Writer @Mailtrap

Devs using macOS, Linux, or Windows who have an affinity for open-source software and a need to build on the .NET (dotnet) platform often go for ASP.NET Core. Add to that the fact that this framework’s latest release, ASP.NET Core version 7.0., is faster than most web frameworks; then it will come as no surprise why it enjoys so much popularity.

In this article, we will do our best to cover the most important aspects of sending emails in ASP.NET Core with C# ranging from plain text emails to emails containing HTML code, attachments, and multiple recipients.

So, without further ado, let’s get to coding!

How to send email using SMTP from ASP.NET Core?

As in most tutorials on our blog, we will start off with the basics – sending a plain text email using an SMTP server.

To make this happen, we need to first complete a few steps.

Step #1 – Create an ASP.NET Core Web API project

All our email-sending code will be contained in one ASP.NET Core Web API project, which can be created in Visual Studio from the File menu. On the menu, select New > Project. Then, in the search box, enter “Web API” and select ASP.NET Core Web API – a project template that can also be used for ASP.NET Core MVC views and controllers.

A new window labeled “Configure your new project” will appear where you need to give your project a name. 

Finally, in the window labeled “Additional information”, choose .NET 7.0 (or later) as the framework and make sure the “Use controllers (uncheck to use minimal APIs)” option is checked before clicking Create.

Step #2 – Integrate your ASP.NET Core project with Swagger UI

Swagger UI is a tool that presents APIs in a user-friendly and easy-to-understand manner so developers, testers, and end consumers can execute and monitor API requests and results. 

By integrating Swagger UI into a project, you will be able to test code easily through a visual interface.

The integration process is initiated by going into the Visual Studio solution explorer and selecting the “Manage NuGet Packages” option. Then, after searching up “swagger” in the “Manage Packages for Solution” window, you need to install the following three that show up as results:

  • Swashbuckle.AspNetCore.Swagger 
  • Swashbuckle.AspNetCore.SwaggerGen
  • Swashbuckle.AspNetCore.SwaggerUI

After the installation, include the Swagger service in the Program.cs file as follows:

services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title = "Example API",
                    Version = "v1",
                    Description = "An example of an ASP.NET Core Web API",
                    Contact = new OpenApiContact
                    {
                        Name = "Example Contact",
                        Email = "example@example.com",
                        Url = new Uri("https://example.com/contact"),
                    },
                });

            });

Also in Program.cs, add:

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();

    app.UseSwaggerUI(options =>
    {
        options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
    });
}

And with that, Swagger UI should be all set up!

Step #3 – Add the MailKit library

MailKit is a library recommended by Microsoft. The company advises devs to use MailKit over the well-known .NET SmtpClient class due to its suitability for modern development. And while you might still see the .NET SmtpClient class in different projects and/or tutorials, remember that it does lack support for many modern protocols.

MailKit installation is quite simple and is done by right-clicking on your ASP. NET Core application project in Visual Studio solution explorer and selecting the “Manage NuGet Packages” option.

Doing this should open a window where you can search for the MailKit NuGet package. Once you find it, click install, and you’re all done!

Note: For this tutorial, we are using version 3.5 of MailKit. If you are using a version other than 3.5, this might result in slight differences, depending on the breaking changes in the newer versions.

Step #4 – Add your SMTP server & email account details to the appsettings.json file

To modify the SMTP server & email account details in your appsettings.json file, just follow the example below:

 "MailSettings": {
    "Server": "send.smtp.mailtrap.io",
    "Port": 587,
    "SenderName": "Your sender name",
    "SenderEmail": "Your sender email",
    "UserName": "Your username",
    "Password": "Your password"
  }

You are free to use any SMTP server of your choice and include its name and other details in appsettings.json

In a lot of tutorials, you will see mentions of the Gmail email solution and its SMTP server, smtp.gmail.com.

In our case, we opted for one provided by Mailtrap Email Sending as its SMTP Service is capable of delivering emails to recipients’ inboxes just in time, and the sending solution itself can do much more (we’ll touch upon this a bit later in the article).

Retrieving Mailtrap SMTP server details and completing the whole setup process is quite straightforward and consists of the following steps:

First, create a Mailtrap account.

Next, proceed to add and verify a domain as described on the Sending Domain Setup page of the Mailtrap knowledgebase. 

Finally, with your domain verified, copy the SMTP details from the API and SMTP Integration page of your Mailtrap account and paste them into your project code.

Step #5 – Make the SMTP server & email account details readable at runtime

Adding SMTP server & email account details into the appsettings.json file does make them part of the project, but it doesn’t make them readable at runtime. For this, you’ll need to create a new folder named “Configuration” at the root of your project and, within it, a file containing a new class.

The class code should look something like this:

public class MailSettings
{
    public string Server { get; set; }
    public int Port { get; set; }
    public string SenderName { get; set; }
    public string SenderEmail { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
}

The loading of data from appsettings.json into the new class will be done by the Configure method in Program.cs once you add this line of code:

builder.Services.Configure<MailSettings>(builder.Configuration.GetSection("MailSettings"));

Step #6 – Write the email-sending code 

Unlike some other programming languages/frameworks, in ASP.NET Core, the email-sending code is written in multiple different documents across a number of folders.

First, you create a model that will hold the data necessary to send an email:

public class MailData
{
    public string EmailToId { get; set; }
    public string EmailToName { get; set; }
    public string EmailSubject { get; set; }
    public string EmailBody { get; set; }
}

Then, you move on to creating (in separate documents) an email-sending interface and a service implementing that interface in a folder named “Services” at the root of our project.

Interface code:

public interface IMailService
{
    bool SendMail(MailData mailData);
}

Email service code: 

public class MailService : IMailService
{
    private readonly MailSettings _mailSettings;
    public MailService(IOptions<MailSettings> mailSettingsOptions)
    {
        _mailSettings = mailSettingsOptions.Value;
    }

    public bool SendMail(MailData mailData)
    {
        try
        {
            using (MimeMessage emailMessage = new MimeMessage())
            {
                MailboxAddress emailFrom = new MailboxAddress(_mailSettings.SenderName, _mailSettings.SenderEmail);
                emailMessage.From.Add(emailFrom);
                MailboxAddress emailTo = new MailboxAddress(mailData.EmailToName, mailData.EmailToId);
                emailMessage.To.Add(emailTo);

                emailMessage.Cc.Add(new MailboxAddress("Cc Receiver", "cc@example.com"));
                emailMessage.Bcc.Add(new MailboxAddress("Bcc Receiver", "bcc@example.com"));

                emailMessage.Subject = mailData.EmailSubject;

                BodyBuilder emailBodyBuilder = new BodyBuilder();
                emailBodyBuilder.TextBody = mailData.EmailBody;

                emailMessage.Body = emailBodyBuilder.ToMessageBody();
                //this is the SmtpClient from the Mailkit.Net.Smtp namespace, not the System.Net.Mail one
                using (SmtpClient mailClient = new SmtpClient())
                {
                    mailClient.Connect(_mailSettings.Server, _mailSettings.Port, MailKit.Security.SecureSocketOptions.StartTls);
                    mailClient.Authenticate(_mailSettings.UserName, _mailSettings.Password);
                    mailClient.Send(emailMessage);
                    mailClient.Disconnect(true);
                }
            }

            return true;
        }
        catch (Exception ex)
        {
            // Exception Details
            return false;
        }
    }
}

The service above now needs to be registered inside the application container. This is done in the Program.cs file.

builder.Services.AddTransient<IMailService, MailService>();

Lastly, to inject the service into an API controller with the help of dependency injection and also add a POST method that will send off the email, create a new file under “Controllers” and populate it with the following lines of code:

  [ApiController]
    [Route("[controller]")]
    public class MailController : ControllerBase
    {
        private readonly IMailService _mailService;
        //injecting the IMailService into the constructor
        public MailController(IMailService _MailService)
        {
            _mailService = _MailService;
        }

        [HttpPost]
        [Route("SendMail")]
        public bool SendMail(MailData mailData)
        {
            return _mailService.SendMail(mailData);
        }
    }

Run your project and use Swagger UI to see how everything works.

By navigating to https://localhost:<port>/swagger, you will see all the controllers created and the methods within, which in our case, are the Mail controller and the SendMail method. The SendMail method should come with a “Try it out” button, which you can use to send your first email.

Here is an example of how an email-sending request looks like in Swagger:

Sending an Email in ASP.NET Core Asynchronously

Devs using ASP.NET Core most likely care about having great performance, which is why they decided to go for one of the fastest web frameworks.

To further improve performance, avoid any potential bottlenecks, and improve the responsiveness of their applications, they might also choose to send email async, and here is how!

Add a new method signature to the IMailService interface as follows:

Task<bool> SendMailAsync(MailData mailData);

Then, just add the async version of the method implementation to the service class MailService.

public async Task<bool> SendMailAsync(MailData mailData)
    {
        try
        {
            using (MimeMessage emailMessage = new MimeMessage())
            {
                MailboxAddress emailFrom = new MailboxAddress(_mailSettings.SenderName, _mailSettings.SenderEmail);
                emailMessage.From.Add(emailFrom);
                MailboxAddress emailTo = new MailboxAddress(mailData.EmailToName, mailData.EmailToId);
                emailMessage.To.Add(emailTo);

                // you can add the CCs and BCCs here.
                //emailMessage.Cc.Add(new MailboxAddress("Cc Receiver", "cc@example.com"));
                //emailMessage.Bcc.Add(new MailboxAddress("Bcc Receiver", "bcc@example.com"));

                emailMessage.Subject = mailData.EmailSubject;

                BodyBuilder emailBodyBuilder = new BodyBuilder();
                emailBodyBuilder.TextBody = mailData.EmailBody;

                emailMessage.Body = emailBodyBuilder.ToMessageBody();
                //this is the SmtpClient from the Mailkit.Net.Smtp namespace, not the System.Net.Mail one
                using (SmtpClient mailClient = new SmtpClient())
                {
                    await mailClient.ConnectAsync(_mailSettings.Server, _mailSettings.Port, MailKit.Security.SecureSocketOptions.StartTls);
                    await mailClient.AuthenticateAsync(_mailSettings.UserName, _mailSettings.Password);
                    await mailClient.SendAsync(emailMessage);
                    await mailClient.DisconnectAsync(true);
                }
            }

            return true;
        }
        catch (Exception ex)
        {
            // Exception Details
            return false;
        }
    }

And that is it!

Now run the code, and your email should be sent asynchronously.

How to send emails from ASP.NET Core using an email API?

Sending emails using an SMTP server is the traditional way of going about it. And don’t get us wrong. In this case, traditional doesn’t mean bad. Instead, it just means that doing most of the manual work will be your responsibility.

Those wanting to avoid this will often opt for using an email API as the right one can represent an automated, straightforward, and feature-packed solution.

With Mailtrap Email Sending, you can get both – an SMTP and an email API. And since we have covered the former already, it’s time to talk about the email API as well as the features at the disposal of devs using Mailtrap Email Sending to deliver emails.

Mailtrap Email Sending’s reliable email API offers users a smooth as well as secure setup and an integration process consisting of simply copy-pasting a configuration code into your project and running it. 

For ASP.NET Core, at the moment of writing, there isn’t an available configuration code within the Mailtrap Email Sending dashboard. But no worries, as we’ll provide everything you need here and guide you through all the steps!

First, add the properties ApiToken and ApiBaseUrl in the MailSettings.cs file:

public string ApiToken { get; set; }
public string ApiBaseUrl { get; set;}

Then in appSettings.json, define the values for the above properties. 

"ApiToken": "Get your api token from your MailTrap account",
"ApiBaseUrl": "https://send.api.mailtrap.io/api/"

Once that is done, you need to add a named HttpClient to the application’s service container by including this code in the Services configuration section of the Program.cs file:

builder.Services.AddHttpClient("MailTrapApiClient", (services, client) =>
{
    var mailSettings = services.GetRequiredService<IOptions<MailSettings>>().Value;
    client.BaseAddress = new Uri(mailSettings.ApiBaseUrl);
    client.DefaultRequestHeaders.Add("Api-Token", mailSettings.ApiToken);
});

Next, create a new service for sending emails using the Mailtrap Email Sending API by adding an interface called IAPIMailService in the “Services” folder.

public interface IAPIMailService
    {
        Task<bool> SendMailAsync(MailData mailData);
        Task<bool> SendHTMLMailAsync(HTMLMailData htmlMailData);
        Task<bool> SendMailWithAttachmentsAsync(MailDataWithAttachment mailDataWithAttachment);
    }

In the same folder, create a class called APIMailService which implements the IAPIMailService interface. And in the constructor of the class, inject the MailSettings class and the IHttpClientFactory interface.

public class APIMailService : IAPIMailService
    {
        private readonly MailSettings _mailSettings;
        private readonly HttpClient _httpClient;

        public APIMailService(IOptions<MailSettings> mailSettingsOptions, IHttpClientFactory httpClientFactory)
        {
            _mailSettings = mailSettingsOptions.Value;
            _httpClient = httpClientFactory.CreateClient("MailTrapApiClient");
        }

        public async Task<bool> SendHTMLMailAsync(HTMLMailData htmlMailData)
        {
            string filePath = Directory.GetCurrentDirectory() + "\\Templates\\Hello.html";
            string emailTemplateText = File.ReadAllText(filePath);

            var htmlBody = string.Format(emailTemplateText, htmlMailData.EmailToName, DateTime.Today.Date.ToShortDateString());

            var apiEmail = new
            {
                From = new { Email = _mailSettings.SenderEmail, Name = _mailSettings.SenderEmail },
                To = new[] { new { Email = htmlMailData.EmailToId, Name = htmlMailData.EmailToName } },
                Subject = "Hello",
                Html = htmlBody
            };

            var httpResponse = await _httpClient.PostAsJsonAsync("send", apiEmail);

            var responseJson = await httpResponse.Content.ReadAsStringAsync();
            var response = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseJson);

            if (response != null && response.TryGetValue("success", out object? success) && success is bool boolSuccess && boolSuccess)
            {
                return true;
            }

            return false;
        }

        public async Task<bool> SendMailAsync(MailData mailData)
        {
            var apiEmail = new
            {
                From = new { Email = _mailSettings.SenderEmail, Name = _mailSettings.SenderEmail },
                To = new[] { new { Email = mailData.EmailToId, Name = mailData.EmailToName } },
                Subject = mailData.EmailSubject,
                Text = mailData.EmailBody
            };

            var httpResponse = await _httpClient.PostAsJsonAsync("send", apiEmail);

            var responseJson = await httpResponse.Content.ReadAsStringAsync();
            var response = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseJson);

            if (response != null && response.TryGetValue("success", out object? success) && success is bool boolSuccess && boolSuccess)
            {
                return true;
            }

            return false;
        }

        public async Task<bool> SendMailWithAttachmentsAsync(MailDataWithAttachment mailDataWithAttachment)
        {
            var attachments = new List<object>();
            if (mailDataWithAttachment.EmailAttachments != null)
            {
                foreach (var attachmentFile in mailDataWithAttachment.EmailAttachments)
                {
                    if (attachmentFile.Length == 0)
                    {
                        continue;
                    }

                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        await attachmentFile.CopyToAsync(memoryStream);
                        attachments.Add(new
                        {
                            FileName = attachmentFile.FileName,
                            Content = Convert.ToBase64String(memoryStream.ToArray()),
                            Type = attachmentFile.ContentType,
                            Disposition = "attachment" // or inline
                        });
                    }
                }
            }

            var apiEmail = new
            {
                From = new { Email = _mailSettings.SenderEmail, Name = _mailSettings.SenderEmail },
                To = new[] { new { Email = mailDataWithAttachment.EmailToId, Name = mailDataWithAttachment.EmailToName } },
                Subject = mailDataWithAttachment.EmailSubject,
                Text = mailDataWithAttachment.EmailBody,
                Attachments = attachments.ToArray()
            };

            var httpResponse = await _httpClient.PostAsJsonAsync("send", apiEmail);

            var responseJson = await httpResponse.Content.ReadAsStringAsync();
            var response = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseJson);

            if (response != null && response.TryGetValue("success", out object? success) && success is bool boolSuccess && boolSuccess)
            {
                return true;
            }

            return false;
        }
    }

A controller will also need to be created in the “Controllers” folder, which you can do as follows:

 [Route("[controller]")]
    [ApiController]
    public class MailAPIController : ControllerBase
    {
        private readonly IAPIMailService _apiMailService;

        //injecting the IMailService into the constructor
        public MailAPIController(IAPIMailService apiMailService)
        {
            _apiMailService = apiMailService;
        }

        [HttpPost]
        [Route("SendMailAsync")]
        public async Task<bool> SendMailAsync(MailData mailData)
        {
            return await _apiMailService.SendMailAsync(mailData);
        }

        [HttpPost]
        [Route("SendHTMLMailAsync")]
        public async Task<bool> SendHTMLMailAsync(HTMLMailData htmlMailData)
        {
            return await _apiMailService.SendHTMLMailAsync(htmlMailData);
        }

        [HttpPost]
        [Route("SendMailWithAttachmentAsync")]
        public async Task<bool> SendMailWithAttachmentAsync([FromForm] MailDataWithAttachment mailDataWithAttachment)
        {
            return await _apiMailService.SendMailWithAttachmentsAsync(mailDataWithAttachment);
        }

    }

Finally, register the service you created earlier in the Program.cs file, and you should be all set. 

builder.Services.AddTransient<IAPIMailService, APIMailService>();

If you need further help with Mailtrap Email Sending and its API or SMTP service, feel free to check out the related documentation. 

Once added to your .NET Core app project, the above code snippets will integrate Mailtrap Email Sending into it and thus enable you to send emails with an average delivery time of ≈ 1 sec, stay on top of deliverability numbers, and troubleshoot any unexpected sending issues quickly and easily using unique monitoring features which include:

  • helicopter-view dashboards
  • drill-down email reports for mailbox providers 
  • extended email history with historical data up to 60 days 
  • email body preview after the email was sent 
  • weekly reports with week-on-week comparison 
  • critical alerts if numbers suddenly drop

And yes, regardless of whether you go with Mailtrap Email Sending’s API or SMTP service, you get the same features and benefits we mentioned. The only difference will be in the integration process!

How to send an HTML email in ASP.NET Core?

Thus far, our focus has been on sending plain text emails. And while these do get the job done when it comes to communicating your messages, at least the simple ones, they aren’t something that will catch the recipients’ attention and engage them. For this, you’ll need to use HTML emails. 

To send HTML email using MailKit in ASP.NET Core, you will again need to complete a few steps.

Step #1 – Create an email template

In the “Templates” folder of your project, create a new .html file and populate it with some code. 

<head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Hello</title>
    </head>
    <body>
        <h1>Hello fellow coder {0}!</h1>
        <p>
            We hope this tutorial will come in handy for your ASP.NET Core project 🙂
        </p>
        <p>Thanks for reading!</p>
        <p>{1}</p>
    </body>

Step #2 – Create a new model

For a plain text email, you needed a model that will hold the data necessary for sending the email. And the same applies to the HTML version. 

public class HTMLMailData
{
   public string EmailToId { get; set; }
   public string EmailToName { get; set; }
}

As you can see, the above model does not include the email subject or body. This is because both are now part of the HTML template we created earlier.

Step #3 – Make changes to IMailService and MailService

In the IMailService interface, you need to add a new method that will use the HTMLMailData model and do the sending. 

public interface IMailService
{
    bool SendMail(MailData MailData);
    bool SendHTMLMail(HTMLMailData htmlMailData);
}

Once you’ve done that, write the method’s implementation in MailService.

   public bool SendHTMLMail(HTMLMailData htmlMailData)
    {
        try
        {
            using (MimeMessage emailMessage = new MimeMessage())
            {
                MailboxAddress emailFrom = new MailboxAddress(_mailSettings.SenderName, _mailSettings.SenderEmail);
                emailMessage.From.Add(emailFrom);

                MailboxAddress emailTo = new MailboxAddress(htmlMailData.EmailToName, htmlMailData.EmailToId);
                emailMessage.To.Add(emailTo);

                emailMessage.Subject = "Hello";

                string filePath = Directory.GetCurrentDirectory() + "\\Templates\\Hello.html";
                string emailTemplateText = File.ReadAllText(filePath);

                emailTemplateText = string.Format(emailTemplateText, htmlMailData.EmailToName, DateTime.Today.Date.ToShortDateString());

                BodyBuilder emailBodyBuilder = new BodyBuilder();
                emailBodyBuilder.HtmlBody = emailTemplateText;
                emailBodyBuilder.TextBody = "Plain Text goes here to avoid marked as spam for some email servers.";

                emailMessage.Body = emailBodyBuilder.ToMessageBody();
                
                using (SmtpClient mailClient = new SmtpClient())
                {
                    mailClient.Connect(_mailSettings.Server, _mailSettings.Port, MailKit.Security.SecureSocketOptions.StartTls);
                    mailClient.Authenticate(_mailSettings.SenderEmail, _mailSettings.Password);
                    mailClient.Send(emailMessage);
                    mailClient.Disconnect(true);
                }
            }

            return true;
        }
        catch (Exception ex)
        {
            // Exception Details
            return false;
        }
    }

Step #4 – Add a new method in the Mail controller

Lastly, in the Mail controller, create a new POST method.

 [HttpPost]
 [Route("SendHTMLMail")]
 public bool SendHTMLMail(HTMLMailData htmlMailData)
 {
   return _mailService.SendHTMLMail(htmlMailData);
 }

How to send email with attachment in ASP.NET Core?

As one would assume, sending an email with an attachment is quite easy.

You begin with creating a new model which derives from the MailData model.

public class MailDataWithAttachment : MailData
{
    public IFormFileCollection EmailAttachments { get; set; }
}

Then, add a new method in the IMailService interface.

public interface IMailService
{
    bool SendMail(MailData mailData);
    bool SendHTMLMail(HTMLMailData htmlMailData);
    bool SendMailWithAttachment(MailDataWithAttachment mailData);
}

And implement it in MailService.

  public bool SendMailWithAttachment(MailDataWithAttachment mailData)
    {
        try
        {
            using (MimeMessage emailMessage = new MimeMessage())
            {
                MailboxAddress emailFrom = new MailboxAddress(_mailSettings.SenderName, _mailSettings.SenderEmail);
                emailMessage.From.Add(emailFrom);
                MailboxAddress emailTo = new MailboxAddress(mailData.EmailToName, mailData.EmailToId);
                emailMessage.To.Add(emailTo);

                // you can add the CCs and BCCs here.
                //emailMessage.Cc.Add(new MailboxAddress("Cc Receiver", "cc@example.com"));
                //emailMessage.Bcc.Add(new MailboxAddress("Bcc Receiver", "bcc@example.com"));

                emailMessage.Subject = mailData.EmailSubject;

                BodyBuilder emailBodyBuilder = new BodyBuilder();
                emailBodyBuilder.TextBody = mailData.EmailBody;

                if (mailData.EmailAttachments != null)
                {
                    foreach (var attachmentFile in mailData.EmailAttachments)
                    {
                        if (attachmentFile.Length == 0)
                        {
                            continue;
                        }

                        using (MemoryStream memoryStream = new MemoryStream())
                        {
                            attachmentFile.CopyTo(memoryStream);
                            var attachmentFileByteArray = memoryStream.ToArray();

                            emailBodyBuilder.Attachments.Add(attachmentFile.FileName, attachmentFileByteArray, ContentType.Parse(attachmentFile.ContentType));
                        }
                    }
                }

                emailMessage.Body = emailBodyBuilder.ToMessageBody();
                //this is the SmtpClient from the Mailkit.Net.Smtp namespace, not the System.Net.Mail one
                using (SmtpClient mailClient = new SmtpClient())
                {
                    mailClient.Connect(_mailSettings.Server, _mailSettings.Port, MailKit.Security.SecureSocketOptions.StartTls);
                    mailClient.Authenticate(_mailSettings.UserName, _mailSettings.Password);
                    mailClient.Send(emailMessage);
                    mailClient.Disconnect(true);
                }
            }

            return true;
        }
        catch (Exception ex)
        {
            // Exception Details
            return false;
        }
    }

To finish things off, you guessed it; you add a new POST method in the Mail controller.

[HttpPost]
 [Route("SendMailWithAttachment")]
 public bool SendMailWithAttachment([FromForm] MailDataWithAttachment mailDataWithAttachment)
 {
   return _mailService.SendMailWithAttachment(mailDataWithAttachment);
 }

How to send an email to multiple recipients in ASP.NET Core?

When it comes to the basics of sending emails in ASP.NET Core, the only one we haven’t covered yet is how to send email to group of users. And if you’re feeling overwhelmed by all the coding thus far, don’t worry; this will only require changing a few lines.

First, put all your recipient addresses into a variable.

var addresses = "firstemail@example.com;secondemail@example.com";

Then, just add each address to the To property of your MimeMessage object using a foreach loop.

 MimeMessage emailMessage = new MimeMessage();
            MailboxAddress emailFrom = new MailboxAddress(_MailSettings.Name, _MailSettings.SenderEmail);
 emailMessage.From.Add(emailFrom);

foreach (var address in addresses.Split(new [] {";"}, StringSplitOptions.RemoveEmptyEntries))
{
     emailMessage.To.Add(address);    
}

In case you want to “CC” or “BCC” specific recipients in your email, simply use the CC or BCC property of your MimeMessage object.

 MimeMessage emailMessage = new MimeMessage();
 emailMessage.Cc.Add(new MailboxAddress("Cc Receiver", "cc@example.com"));
 emailMessage.Bcc.Add(new MailboxAddress("Bcc Receiver", "bcc@example.com"));

Testing emails in ASP.NET Core: why and how?

Even the most talented devs are prone to making errors. Unfortunately, the errors present in your email-sending code can go completely undetected until the email reaches the recipient’s inbox. In other words, when it’s already too late.  

To prevent this from happening, you need to test your project’s/app’s email-sending functionality before you even consider reaching out to real recipients.

Mailtrap Email Testing is a tool designed exactly for this purpose. With it, you can do safe email testing by catching emails from staging to then preview and analyze their content for spam and validate their HTML/CSS before production. And since Mailtrap Email Testing functions on the principle of using virtual inboxes, you aren’t at risk of spamming real recipients with testing emails or cluttering up your personal inbox with junk; plus, it helps preserve your domain reputation.

To start using Email Testing, you need to have a Mailtrap account which already might be the case if you decided on using Mailtrap Email Sending to deliver your non-testing emails. 

With an active account, log into the Mailtrap dashboard and navigate to Email Testing->Inboxes-> SMTP Settings. There, select the programming language you are using for your project from the Integrations dropdown to have the configuration code generated.

For C#, the configuration code should look something like this:

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

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

Copy this code, paste it into your project, and run everything together. This should result in your first test email being sent.

Once it arrives in your virtual inbox, you can start inspecting and debugging it using the range of features available to you through Email Testing.

Note: An alternative way to start using Mailtrap Email Testing is to just copy the SMTP credentials it provides you with for each of your virtual inboxes (on the same page as the configuration code) and paste them into appsettings.json under MailSettings:

  "MailSettings": {
    "Server": "sandbox.smtp.mailtrap.io",
    "Port": 2525,
    "SenderName": "Your sender name",
    "SenderEmail": "from@example.com",
    "UserName": "your_username",
    "Password": "your_password"
  }

Wrapping things up

Choosing ASP.NET Core for your web development project might be a personal choice or a task requirement, but it will, without a doubt, help build blazing-fast web apps. 

We hope that our instructions will come in handy when you’re implementing one of the crucial features of those apps – sending emails with ASP.NET Core!

If you want to read more content on sending emails with .NET, make sure to check out our ASP.NET send email and C# send email articles. For other technologies, have a look at our blog where you’ll find other useful articles that you may find helpful.

Enjoyed this article on how to send email using ASP.NET Core? Then make sure to share it with your fellow devs!

Article by Dzenana Kajtaz Technical Content Writer @Mailtrap

I’m a Technical Content Writer with an educational background in software engineering and 4 years of experience as a writer, editor, and content marketer. Currently, I mainly focus on writing about email infrastructure, sending, testing, and so on, but I do love creating fun and engaging content on email marketing topics as well.