If you are porting web applications to ASP.NET Core or building new web applications, you may notice that the System.Net.Mail namespace is not implemented in .NET Core. My understanding is that there are intentions to implement that namespace later, but it may be a little stumbling block for early adopters, since sending email is a very fundamental thing that most web applications need to do for common tasks such as verifying an email address for a new account or facilitating password reset.

There are some examples out there for sending email with various 3rd party services such as SendGrid, MailGun, Elastic Email, and the like, by using REST APIs to send the mail instead of using SMTP, and that is certainly a good option to consider. But for those who already have an SMTP server that they want to use, a better solution is needed. The good news is a better solution already exists and it works currently with RC1 of ASP.NET Core and will most surely also be available for RC2 and later releases.

There are actually 2 related projects that you should know about, MailKit and MimeKit. The goal of the MailKit project is “to provide the .NET world with robust, fully featured and RFC-compliant SMTP, POP3, and IMAP client implementations”, and indeed it meets that goal and in many ways is actually more powerful and flexible than the traditional System.Net.Mail components.

Here I will show some working example code that comes from my cloudscribe Core project. More specifically this example code is from my EmailSender class which is a work in progress, but functional enough to be a good example.

Lets start with a simple class to represent and encapsulate the settings we need to connect and authenticate with an SMTP Server:

public class SmtpOptions
{
    public string Server { get; set; } = string.Empty;
    public int Port { get; set; } = 25;
    public string User { get; set; } = string.Empty;
    public string Password { get; set; } = string.Empty;
    public bool UseSsl { get; set; } = false;
    public bool RequiresAuthentication { get; set; } = false;
    public string PreferredEncoding { get; set; } = string.Empty;
}

You would new up one of these and set the properties according to your SMTP server configuration, then you would pass that in as one of the parameters to an EmailSender class that looks something like this:

using MailKit.Net.Smtp;
using MimeKit;
using System;
using System.Threading.Tasks;

namespace cloudscribe.Messaging.Email
{

    public class EmailSender
    {
        public EmailSender()
        {
        }

        public async Task SendEmailAsync(
            SmtpOptions smtpOptions,
            string to,
            string from,
            string subject,
            string plainTextMessage,
            string htmlMessage,
            string replyTo = null)
        {
            if (string.IsNullOrWhiteSpace(to))
            {
                throw new ArgumentException("no to address provided");
            }

            if (string.IsNullOrWhiteSpace(from))
            {
                throw new ArgumentException("no from address provided");
            }

            if (string.IsNullOrWhiteSpace(subject))
            {
                throw new ArgumentException("no subject provided");
            }

            var hasPlainText = !string.IsNullOrWhiteSpace(plainTextMessage);
            var hasHtml = !string.IsNullOrWhiteSpace(htmlMessage);
            if (!hasPlainText && !hasHtml)
            {
                throw new ArgumentException("no message provided");
            }

            var m = new MimeMessage();
          
            m.From.Add(new MailboxAddress("", from));
            if(!string.IsNullOrWhiteSpace(replyTo))
            {
                m.ReplyTo.Add(new MailboxAddress("", replyTo));
            }
            m.To.Add(new MailboxAddress("", to));
            m.Subject = subject;

            //m.Importance = MessageImportance.Normal;
            //Header h = new Header(HeaderId.Precedence, "Bulk");
            //m.Headers.Add()

            BodyBuilder bodyBuilder = new BodyBuilder();
            if(hasPlainText)
            {
                bodyBuilder.TextBody = plainTextMessage;
            }

            if (hasHtml)
            {
                bodyBuilder.HtmlBody = htmlMessage;
            }

            m.Body = bodyBuilder.ToMessageBody();
           
            using (var client = new SmtpClient())
            {
                await client.ConnectAsync(
                    smtpOptions.Server,
                    smtpOptions.Port,
                    smtpOptions.UseSsl)
                    .ConfigureAwait(false);
               
                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                // Note: only needed if the SMTP server requires authentication
                if(smtpOptions.RequiresAuthentication)
                {
                    await client.AuthenticateAsync(smtpOptions.User, smtpOptions.Password)
                        .ConfigureAwait(false);
                }
               
                await client.SendAsync(m).ConfigureAwait(false);
                await client.DisconnectAsync(true).ConfigureAwait(false);
            }

        }

        public async Task SendMultipleEmailAsync(
            SmtpOptions smtpOptions,
            string toCsv,
            string from,
            string subject,
            string plainTextMessage,
            string htmlMessage)
        {
            if (string.IsNullOrWhiteSpace(toCsv))
            {
                throw new ArgumentException("no to addresses provided");
            }

            if (string.IsNullOrWhiteSpace(from))
            {
                throw new ArgumentException("no from address provided");
            }

            if (string.IsNullOrWhiteSpace(subject))
            {
                throw new ArgumentException("no subject provided");
            }

            var hasPlainText = !string.IsNullOrWhiteSpace(plainTextMessage);
            var hasHtml = !string.IsNullOrWhiteSpace(htmlMessage);
            if (!hasPlainText && !hasHtml)
            {
                throw new ArgumentException("no message provided");
            }

            var m = new MimeMessage();
            m.From.Add(new MailboxAddress("", from));
            string[] adrs = toCsv.Split(',');

            foreach (string item in adrs)
            {
                if (!string.IsNullOrEmpty(item)) { m.To.Add(new MailboxAddress("", item)); ; }
            }

            m.Subject = subject;
            m.Importance = MessageImportance.High;
          
            BodyBuilder bodyBuilder = new BodyBuilder();
            if (hasPlainText)
            {
                bodyBuilder.TextBody = plainTextMessage;
            }

            if (hasHtml)
            {
                bodyBuilder.HtmlBody = htmlMessage;
            }

            m.Body = bodyBuilder.ToMessageBody();

            using (var client = new SmtpClient())
            {
                await client.ConnectAsync(
                    smtpOptions.Server,
                    smtpOptions.Port,
                    smtpOptions.UseSsl).ConfigureAwait(false);
               
                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                // Note: only needed if the SMTP server requires authentication
                if (smtpOptions.RequiresAuthentication)
                {
                    await client.AuthenticateAsync(
                        smtpOptions.User,
                        smtpOptions.Password).ConfigureAwait(false);
                }

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

        }

    }
}

Note that I’ve implemented 2 methods here, one that sends email to a single recipient and one that takes a comma separated list of recipients. This code could probably be refactored a bit to reduce duplication, I actually plan to implement more overloads for handling things like attachments. This is just an initial working stub that I plan to evolve as I encounter more varied needs in my project. Note that you can pass in either or both an html formatted message or plain text, but you must of course at least pass in one of them. I’ve left a few comments in the code to show how things like message importance can be set, but really I’ve only scratched the surface of what MailKit/MimeKit can do for you, so I encourage you to explore the available api surface of those projects.

Feel free to borrow this code and use it in your own projects, and I hope you will also take a look at my various open source projects on github that may be of use or value to you on your projects.

Happy Coding!!!

Dear Harris Teeter,

I really did not want to have to write this post, but I told you I would and I’m a man of my word.

First let me say that I like Harris Teeter in general, you have good produce and good meats, staff is generally very nice and helpful, prices are reasonable. You were born here in North Carolina and I like to support businesses from my home state. If it were not for your good qualities I would not bother with this post I would just stop shopping there, but I like Harris Teeter enough to try and make it better.

Therefore I’m going to try to get you to change the one really bad thing you do that makes me very uncomfortable when shopping there (and I assume it makes some other people feel uncomfortable too). If I cannot get you to change after trying my best then I will have no choice as a man of principle than to stop shopping there.

So What’s My Beef?

I’m really sick of hearing “security scan cameras”, “security scan and record all cameras”, “security scan cameras E and F”, and all the other variants that I’ve been hearing for many years while shopping at your store.

I have complained in the past at my local store and I have emailed your headquarters and tweeted at you about this in hopes that you would do the right thing. I told you that 140 characters on twitter is not enough to express why this practice is wrong and must be stopped and that I would write a blog post to shame you into changing if needed. I waited, but you have not done the right thing, so here we are.

The thing is, this voice that announces variations of “security scan cameras” is not a robot voice, it is one of the staff. When I first heard it I thought hmm, must be someone suspicious in the store. But for someone who shops frequently, when you tend to hear that about 80-90% of the times you shop there, when you hear it soon after entering the store, you start thinking maybe it is me they think is suspicious. And that makes me feel uncomfortable. And the more I think about it the more it bothers me. Even if it isn’t me, who is it and what makes them suspicious? The way they are dressed, the color of their skin, etc. Being a person who has empathy for my fellow humans this bothers me and I cannot support a business that does this.

Now when I have complained I have been told those announcements are random. But you know what, having a policy to randomly do that also gives cover to do it for other reasons so while I would like to believe you are not profiling people, I really cannot rule that out, and that bothers me.  If it really is random, does it make sense to randomly make customers feel like suspects? Business marketing 101 says no!

It does not make sense to make customers feel uncomfortable while shopping, and it does not make sense for me to keep shopping at a place that persists in a practice that makes me uncomfortable.

So I started thinking about why you have this policy, you must think it is beneficial, you have made it clear it is part of “loss prevention” strategy. I think the reason this has not backfired on you until now is because the average clean cut white person who hears that is not going to think they are the suspicious one in the store. Some people might say you are using “white priviledge” as part of the psychology for your loss prevention scheme. Here in the South, you might could get away with that for years in the past but the time has come for that to stop. For the record, I’m a white person but I am not immune to negative stereotype profiling because I have long hair. Some conservative folks frown on that sort of thing and make negative assumptions about you based on that. But there are many superficial things that people get profiled on, skin color, tattoos, skin piercing etc, etc, so even white people may not feel the white privilege in every case. I applaud the unique individuals who have the courage to be who they are and express themselves through personal style in spite of knowing how some people will judge them. I have long felt the societal pressure to conform, and even today if I were not self employed I think I would have a hard time getting some jobs for which I am very qualified without cutting my hair. I “could” cut my hair and perhaps then I could go back to assuming those announcements are not targeted at me, but that would be giving up a little piece of my self dignity. For people of color, my empathy says they probably also feel uncomfortable when they hear those announcements in your store.

I don’t want to stop shopping there without first doing my best to make you change this practice. So I plan to tweet a link to this post and my dismay every time I hear that when I shop at your store. If after 12 months of doing that you won’t change then I will stop shopping there and I will also encourage everyone I know to boycott your store.

The bottom line is I will not tolerate this treatment towards me, and I will not tolerate this treatment towards others indefinitely. I implore you to do the right thing and change this policy.

What Do I Suggest?

Look, I can hear the devil’s advocate arguments in my head saying “but loss prevention is important, if our losses go up we have to charge you more and you don’t want that right?” My answer to that is, I don’t hear this in other stores, and I would rather pay for my groceries with money than pay with my dignity.

What I suggest is make a recording and play it as often as you wish, but the recording should not imply that there is someone suspicious in the store. A good message alternative that I can think of is:

“For your safety this store is monitored by full coverage video surveillance.” That still sends a message to potential would be shop lifters to make them think twice, and it puts a positive spin on the surveillance policy. People expect to be under surveillance while shopping so this kind of message is acceptable. But a message that makes customers feel like suspects is simply not acceptable and it must stop for the long term benefit of the Harris Teeter brand. Your new parent company Kroger does not make customers feel like suspects, so maybe you need your parent to have a talk with you.

I Invite help from anyone who reads this and who agrees with me to join me in the effort to make Harris Teeter do the right thing. If you shop there pay attention, and if you hear similar messages and you agree they should stop, then tweet a link to this post and express your dismay to @HarrisTeeter on twitter. And if you are a human with empathy towards other humans I think you should care about this. The world is full of bigger problems but this is something where a small positive change is needed and it would take very little effort to help make that small change happen. Please also keep an eye on my tweets and retweet me when I tweet my dismay towards @HarrisTeeter, you can follow my tweets at @joeaudette

Companies use twitter as an important tool in their marketing and they do not like to see a lot of negative sentiment tweets about their brand. If we join together using the power of social media we can influence Harris Teeter to do the right thing. I’m going to try that for up to a year from now. If they tell me they have changed the policy and if I stop hearing the dreaded announcements then I will update this post or even take it down. I’m trying to create positive change, I did not want to make a stink about this, but it seems that is what it will take.

UPDATE 2016-05-10
Today was my first time shopping at Harris Teeter since making this post. In less than 30 seconds after entering the store I hear a man's voice come over the speaker and say "security scan and record camera A". I'm pretty sure that is their way of flipping me the bird and telling me they are dug in on this policy and don't want me shopping there. So I'm about to tweet "another #badexperience shopping at #harristeeter today with a link to this post and cc @HarrisTeeter. Guess I will also make another public post about it on Facebook too. So to me it seems that they are not so worried about loss prevention because they don't care if they lose customers who are bothered by this policy. Nevertheless, I intend to keep shopping there and keep tweeting and posting whenever this happens and try to spread more awareness about this bad practice. They seem pretty dug in though so I'm not optimistic that there is any humanistic leadership at that organization and in time I may have to go full boycott mode.

UPDATE 2016-05-10 - evening

After reflecting on today's experience I've decided life is too short, and I'm just not going back to Harris Teeter, it is not worth the effort and they clearly don't want me there. If you decide yourself to stop shopping there for the same reason as me, please at least send them a parting tweet linking to this post and telling them they lost another customer.