A common need in both the world of systems management and automation is to be able to send an email automatically, without user intervention, either periodically or when a specific alert or event occurs.
For example, we can define a notification for a system failure, the installation of specific software, intrusion alerts, water level alarms, or the periodic sending of a report with server usage statistics, warehouse stock status… among endless possibilities.
There are different ways to send an email from a program, but a really simple one is to take advantage of the interconnectivity provided by the .NET Framework. This way, we can use Outlook to send an email without any user intervention on any computer that has an account correctly set up.
Preparing the Project
To use the function, we can create a new C# project in Visual Studio, or simply use an existing previous project.
Once we have the project ready and properly configured we must add the following references:
- Microsoft.Office.Interop.Outlook
Once added, we can proceed to code our function.
Function Code
Below is the function that performs the sending. It receives as parameters the address, the subject field, and the main content. We can use HTML to format the email content, or use plain text.
public static Boolean SendEmailWithOutlook(string mailDirection, string mailSubject, string mainContent)
{
try
{
var oApp = new Outlook.Application();
Microsoft.Office.Interop.Outlook.NameSpace ns = oApp.GetNamespace("MAPI");
var f = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
System.Threading.Thread.Sleep(1000);
var mailItem = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
mailItem.Subject = mailSubject;
mailItem.HTMLBody = mailContent;
mailItem.To = mailDirection;
mailItem.Send();
}
catch (Exception ex)
{
return false;
}
finally
{
}
return true;
}
As you can see, it’s a really simple code. We simply create an Outlook application object and use it to create a new email. Then we assign the address, subject, and content, and finally proceed to send it.
Using the Function
Using the function is equally simple. Below is an example directly from the Main function.
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
string mailDirection = @"[email protected]";
string mailSubject = "Subject test";
string mainContent;
mainContent = "Test message";
mainContent += "<br>" + "Another line";
mainContent += "<br>" + "Another line";
SendEmailWithOutlook(mailDirection, mailSubject, mailContent);
}
We simply create text strings with the necessary fields and use our function to perform the sending.
As you can see, it’s really simple and convenient to send an email using C# and Outlook. In future posts, we will explain more potential uses of the .NET Framework for interconnecting applications.

