ALLCODE CRAFT

How to send email using C# and Outlook.com

This is a note to myself. I recently had to write this code for the third time in my life in the last 11 years because I did not save it somewhere consumable. So putting it on my blog for future reference.

Why Send Email From C# Code ?

 There are many email automation services available – so why send email from your own C# code ? Well, there are a number of scenarios where you might want to write your own email sender. FOr example:
1. You want to monitor a new system you’re building  while running long overnite tests.
2. You have a service that cannot be tested using off-the shelf software.
3. You want a special transient fault handling logic in your monitoring code

What are the key pieces of sending emails from C# code ?

 You’ll need only a few basic things:
1. An www.outlook.com  email and password
2. The following using directives in your C# code
using System.Net.Mail;  
using System.Net.Mime;
3. The name of the outlook SMTP server – which is smtp-mail.outlook.com 
4. Ensure that you’re using the correct port and ssl is enabled when you try to send the email. This is already done for you in the code below.
SmtpClient client = new SmtpClient();  
client.UseDefaultCredentials = false;  
client.Credentials = new System.Net.NetworkCredential
                      (emailConfig.ClientCredentialUserName,
                       emailConfig.ClientCredentialPassword);   
client.Host = m_HostName;  
client.Port = 25;  
client.EnableSsl = true;

Code Structure

All the action happens in EmailManager class. It basically does two things:
1. It constructs an email message using the MailMessage class provided by the .Net framework.Then this mail message is decorated with all the properties you want in an email like “to”, “from”, “cc”, “subject” and “body”.
2. Next, we send the email message constructed in step 1 using SmtpClient class. 
The full code is given below for the EmailManager class:
using System;  
using System.Net.Mail;  
using System.Net.Mime;  
  
namespace EmailSender  
{  
    public class EmailManager  
    {  
        private string m_HostName; // your email SMTP server  
  
        public EmailManager(string hostName)  
        {  
            m_HostName = hostName;  
        }  
  
        public void SendMail(EmailSendConfigure emailConfig, EmailContent content)  
        {  
            MailMessage msg = ConstructEmailMessage(emailConfig, content);  
            Send(msg, emailConfig);  
        }  
  
        // Put the properties of the email including "to", "cc", "from", "subject" and "email body"  
        private MailMessage ConstructEmailMessage(EmailSendConfigure emailConfig, EmailContent content)  
        {  
            MailMessage msg = new System.Net.Mail.MailMessage();  
            foreach (string to in emailConfig.TOs)  
            {  
                if (!string.IsNullOrEmpty(to))  
                {  
                    msg.To.Add(to);  
                }  
            }  
  
            foreach (string cc in emailConfig.CCs)  
            {  
                if (!string.IsNullOrEmpty(cc))  
                {  
                    msg.CC.Add(cc);  
                }  
            }  
  
            msg.From = new MailAddress(emailConfig.From, 
                                       emailConfig.FromDisplayName,
                                       System.Text.Encoding.UTF8);  
            msg.IsBodyHtml = content.IsHtml;  
            msg.Body = content.Content;  
            msg.Priority = emailConfig.Priority;  
            msg.Subject = emailConfig.Subject;  
            msg.BodyEncoding = System.Text.Encoding.UTF8;  
            msg.SubjectEncoding = System.Text.Encoding.UTF8;  
  
            if (content.AttachFileName != null)  
            {  
                Attachment data = new Attachment(content.AttachFileName, 
                                                 MediaTypeNames.Application.Zip);  
                msg.Attachments.Add(data);  
            }  
  
            return msg;  
        }  
  
        //Send the email using the SMTP server  
        private void Send(MailMessage message, EmailSendConfigure emailConfig)  
        {  
            SmtpClient client = new SmtpClient();  
            client.UseDefaultCredentials = false;  
            client.Credentials = new System.Net.NetworkCredential(
                                  emailConfig.ClientCredentialUserName, 
                                  emailConfig.ClientCredentialPassword);  
            client.Host = m_HostName;  
            client.Port = 25;  // this is critical
            client.EnableSsl = true;  // this is critical
  
            try  
            {  
                client.Send(message);  
            }  
            catch (Exception e)  
            {  
                Console.WriteLine("Error in Send email: {0}", e.Message);  
                throw;  
            }  
            message.Dispose();  
        }  
  
    }  
  
    public class EmailSendConfigure  
    {  
        public string[] TOs { get; set; }  
        public string[] CCs { get; set; }  
        public string From { get; set; }  
        public string FromDisplayName { get; set; }  
        public string Subject { get; set; }  
        public MailPriority Priority { get; set; }  
        public string ClientCredentialUserName { get; set; }  
        public string ClientCredentialPassword { get; set; }  
        public EmailSendConfigure()  
        {  
        }  
    }  
  
    public class EmailContent  
    {  
        public bool IsHtml { get; set; }  
        public string Content { get; set; }  
        public string AttachFileName { get; set; }  
    }  
}
and here’s the driver program:
namespace EmailSender  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            string smtpServer = "smtp-mail.outlook.com";  
            SendEmail(smtpServer);  
        }  
  
        static void SendEmail(string smtpServer)  
        {  
            //Send teh High priority Email  
           EmailManager mailMan = new EmailManager(smtpServer);  
  
            EmailSendConfigure myConfig = new EmailSendConfigure(); 
            // replace with your email userName  
            myConfig.ClientCredentialUserName = "[email protected]";
            // replace with your email account password
            myConfig.ClientCredentialPassword = "password!";   
            myConfig.TOs = new string[] { "[email protected]" };  
            myConfig.CCs = new string[] { };  
            myConfig.From = "<YOUR_ACCOUNT>@outlook.com";  
            myConfig.FromDisplayName = "<YOUR_NAME>";  
            myConfig.Priority = System.Net.Mail.MailPriority.Normal;  
            myConfig.Subject = "WebSite was down - please investigate";  
  
            EmailContent myContent = new EmailContent();  
            myContent.Content = "The following URLs were down - 1. Foo, 2. bar";  
  
            mailMan.SendMail(myConfig, myContent);  
        }  
  
    }  
}

Final thoughts

If the code is hanging at the Send(mailmessage) stage, I’ve found mostly this is a problem with firewall configuration or proxy server configuration if you’re inside a company intranet.
2023 Update: Note that if you need to automate tasks in this modern era, I’d highly recommend using something like Microsoft Power Automate. This is what we internally use for similar tasks.