I use SendGrid and MailKit for sending email in my custom applications written in ASP.Net Core.

But, I always forget the correct settings to use so I'm writing this post for myself. And hopefully it may prove useful to someone else as well!

Here's my EmailService class and interface:

    using MailKit.Net.Smtp;
    using Microsoft.Extensions.Options;
    using MimeKit;
    using System.Threading.Tasks;

    public interface IEmailService {
        Task SendHtmlEmail(string to, string cc, string subject, string html);
    }

    public class EmailService : IEmailService {

        private EmailOptions _emailOptions;

        public EmailService(
            IOptions<EmailOptions> emailOptionsAccessor
            ) {
            _emailOptions = emailOptionsAccessor.Value;
        }

        public async Task SendHtmlEmail(string to, string cc, string subject, string html) {

            // create the mime message
            var message = new MimeMessage {
                Subject = subject,
                Body = new BodyBuilder { HtmlBody = html }.ToMessageBody()
            };

            // add the from/to/cc
            message.From.Add(InternetAddress.Parse(_emailOptions.From));
            message.To.Add(InternetAddress.Parse(to));
            if(!string.IsNullOrEmpty(cc))
                message.Cc.Add(InternetAddress.Parse(cc));

            using (var client = new SmtpClient()) {

                // connect to send grid
                await client.ConnectAsync("smtp.sendgrid.net", 587, false);
                
                // authenticate with your api key
                await client.AuthenticateAsync("apikey", _emailOptions.ApiKey);

                // send the message
                await client.SendAsync(message);

            };

        }

    }

The other dependency in there is my EmailOptions class:

    public class EmailOptions {
        public string From { get; set; }
        public string ApiKey { get; set; }
    }