Sending emails are common in applications. For example, when user registers, we need to send account activation emails. This post summarize the approaches we can use to send emails in .NET Core 1.x and 2.x.

.NET Core 1.x

.NET Core 1.x is based on .NET Standard 1.x libraries. SmtpClient is not implemented yet. Thus we had to use third party libraries to send emails. For example, MailKit. In Azure, you can also choose SendGrid to send emails.

MailKit

Mailkit project is available in GitHub.

https://github.com/jstedfast/MailKit

Sample Code

/// <summary>
         /// Send email
         /// </summary>
         /// <param name="sender"></param>
         /// <param name="recepients"></param>
         /// <param name="subject"></param>
         /// <param name="body"></param>
         /// <param name="isHtml"></param>
         /// <param name="config"></param>
         /// <returns></returns>
         public static async Task<(bool success, string errorMsg)> SendEmailAsync(MailboxAddress sender, MailboxAddress[] recepients, string subject, string body, bool isHtml = true, SmtpConfig config = null)
         {
             MimeMessage message = new MimeMessage();

            message.From.Add(sender);
             message.To.AddRange(recepients);
             message.Subject = subject;
             message.Body = isHtml ? new BodyBuilder { HtmlBody = body }.ToMessageBody() : new TextPart("plain") { Text = body };

            try
             {
                 if (config == null)
                     if (Configuration != null)
                         config = Configuration;

                using (var client = new SmtpClient())
                 {
                     if (!config.UseSSL)
                         client.ServerCertificateValidationCallback = (object sender2, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => true;

                    await client.ConnectAsync(config.Host, config.Port, config.UseSSL).ConfigureAwait(false);
                     client.AuthenticationMechanisms.Remove("XOAUTH2");

                    if (!string.IsNullOrWhiteSpace(config.Username))
                         await client.AuthenticateAsync(config.Username, config.Password).ConfigureAwait(false);

                    await client.SendAsync(message).ConfigureAwait(false);
                     await client.DisconnectAsync(true).ConfigureAwait(false);
                 }

                return (true, null);
             }
             catch (Exception ex)
             {
                 if (LoggerFactory != null)
                     LoggerFactory.CreateLogger<EmailHelpers>().LogError(LoggingEvents.SEND_EMAIL_ERROR, ex, "An error occurred while sending email");
                 return (false, ex.Message);
             }

        }

.NET Core 2.x

SmtpClient is already migrated to .NET Standard 2. Thus we can use built-in library to send emails.

Sample Code

/// <summary>
         /// Send email
         /// </summary>
         /// <param name="sender"></param>
         /// <param name="recepients"></param>
         /// <param name="subject"></param>
         /// <param name="body"></param>
         /// <param name="isHtml"></param>
         /// <param name="config"></param>
         /// <returns></returns>
         public async Task<(bool success, string errorMsg)> SendEmailAsync(MailAddress sender, MailAddress[] recepients, string subject, string body, bool isHtml = true, MailAddress[] bccList = null)
         {
             MailMessage message = new MailMessage
             {
                 From = sender
             };

            message.Subject = subject;
             message.IsBodyHtml = isHtml;
             message.Body = body;
             message.SubjectEncoding = Encoding.UTF8;
             message.BodyEncoding = Encoding.UTF8;
             foreach (var recepient in recepients)
                 message.To.Add(recepient);

            if (bccList != null)
             {
                 foreach (var recepient in recepients)
                     message.Bcc.Add(recepient);
             }

            var emailMessage = AddEmailMessageToStore(message);
             try
             {
                 using (var client = new SmtpClient())
                 {
                     var config = configService.EmailConfig;

                    if (config.EnableSSl)
                         client.EnableSsl = true;
                     client.Host = config.Host;
                     client.Port = config.Port;
                     client.DeliveryMethod = SmtpDeliveryMethod.Network;
                     client.Credentials = new NetworkCredential(config.UserName, rootConfig[config.PasswordConfigurationName]);

                    await client.SendMailAsync(message);
                     emailMessage.IsSent = true;
                     emailMessage.IsSuccessful = true;
                     emailMessage.DateSent = DateTime.Now;
                     emailMessage.DateModified = DateTime.Now;
                     SaveEmailMessage(emailMessage);
                 }

                return (true, null);
             }
             catch (Exception ex)
             {
                 if (loggerFactory != null)
                     loggerFactory.CreateLogger<EmailSenderService>().LogError(LoggingEvents.SEND_EMAIL_ERROR, ex, "An error occurred while sending email");
                 emailMessage.IsSent = false;
                 emailMessage.IsSuccessful = false;
                 emailMessage.Comment = ex.ToString();
                 emailMessage.DateModified = DateTime.Now;
                 SaveEmailMessage(emailMessage);

                return (false, ex.Message);
             }

        }

info Last modified by Raymond at 3 years ago copyright This page is subject to Site terms.

More from Kontext

local_offer .net core

visibility 2534
thumb_up 0
access_time 3 years ago

After upgrading to ASP.NET Core 2.1 (.NET Core SDK 2.1.301), you may encounter the following error about encoding: System.ArgumentException    HResult=0x80070057    Message='Cyrillic' is not a supported encoding name. For information on defining a cus...

open_in_new ASP.NET Core

local_offer sqlite local_offer .net core local_offer entity-framework

visibility 24953
thumb_up 2
access_time 3 years ago

SQLite is a self-contained and embedded SQL database engine. In .NET Core, Entity Framework Core provides APIs to work with SQLite. This page provides sample code to create a SQLite database using package Microsoft.EntityFrameworkCore.Sqlite . Create sample project ...

open_in_new .NET Framework

local_offer asp.net core 2 local_offer .net core

visibility 2507
thumb_up 0
access_time 3 years ago

In .NET Core 2.x, Windows Forms or WPF are not implemented since they are based on GDI+ and DirectX respectively in Windows. In .NET Core 3.0, there is plan to add Desktop Packs which includes UWP. WPF and Windows Forms. However, they will still be Windows-only. In .NET Core applications, you may...

open_in_new ASP.NET Core

local_offer .net core

visibility 6354
thumb_up 0
access_time 3 years ago

.NET core introduces a logging API that works with a number of logging frameworks. The built-in providers are configurable and extensible to support different level loggings.

open_in_new .NET Framework

comment Comments (0)

comment Add comment

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts

No comments yet.

Kontext Column

Created for everyone to publish data, programming and cloud related articles. Follow three steps to create your columns.


Learn more arrow_forward