Read here about Kontext's Cookie and Privacy policy. Dismiss

Sending Emails in .NET Core Applications

1063 views 0 comments last modified about 8 months ago Raymond

.net core

In this page

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

        }

Related pages

Tuples in C# (4.x, 7.0, 7.1)

64 views   0 comments last modified about 3 months ago

What is a tuple? Tuple is an ordered sequence, fixed-size, immutable and of heterogeneous objects. Tuple has been existing in other languages such as F#, Python, Perl and etc. for a long time. It was first introduced into C# from C# 4.0 and has been evolving over time. Since C# 7.1, tuple...

View detail

Invoke Hadoop WebHDFS APIs in .NET Core

99 views   0 comments last modified about 4 months ago

Background Apache doesn't provide native official .NET APIs for Hadoop HDFS. The HTTP REST API supports the complete FileSystem / ...

View detail

Logging configuration in .NET core

188 views   0 comments last modified about 8 months 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.

View detail

Retrieve Http client request metadata like IP address and languages in asp.net core

597 views   0 comments last modified about 8 months ago

IP Address In ASP.NET Core, Request.UserHostAddress has been removed though that attribute exists in the traditional ASP.NET applications. We can use HttpContext.Connection to retrieve the remove client IP address: var ipAddress = HttpContext.Connecti...

View detail

Migrating from ASP.NET Core 1.x to ASP.NET Core 2.0

775 views   2 comments last modified about 9 months ago

Migrating from ASP.NET Core 1.x to 2.0 is not an easy job especially if you have customized Identity and used customized authentication. This post summarizes the issues and errors I have experienced and their resolutions when upgrading my project. Hopefully it can save you sometime if you are doi...

View detail

Migrating from ASP.NET Core 1.x to ASP.NET Core 2.0 – Issues Continued

610 views   0 comments last modified about 9 months ago

Other related issues are found during my migration. Unable to Change Identity Table Names ...

View detail

Add comment

Please login first to add comments.  Log in New user?  Register

Comments (0)

No comments yet.