This site uses cookies to deliver our services. By using this site, you acknowledge that you have read and understand our Cookie and Privacy policy. Your use of Kontext website is subject to this policy. Allow Cookies and Dismiss

Sending Emails in .NET Core Applications

1501 views 0 comments last modified about 12 months ago Raymond

.net core

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

Set AttachDbFilename as Relative Path in .NET Core

145 views   0 comments last modified about 3 months ago

.NET Framework, you can use |DataDirectory| to configure connection string when connecting to SQL Server database file via attach mode: AttachDbFilename=|DataDirectory|\dbname.mdf In .NET Core, you cannot directly set SQL Server Express connec...

View detail

Instantiate a Service in ConfigureServices Method in .NET Core

31 views   0 comments last modified about 3 months ago

.NET Core is built in with dependency injection. Usually method ConfigureServices in Startup class is used to register services in the container. The signature of the method looks like the following: public void ConfigureServices(IServiceC...

View detail

SQLite in .NET Core with Entity Framework Core

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

View detail

Graphics Programming and Image Processing in .NET Core 2.x

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

View detail

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

161 views   0 comments last modified about 7 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

308 views   0 comments last modified about 7 months ago

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

View detail

Add comment

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

Comments (0)

No comments yet.