With this post, we will learn how to connect an application through its API, from a NET6 application written in C#.
As we have mentioned before, integrating different technologies is very necessary in the IoT field. Previously, we have seen how to connect with Microsoft Word and Microsoft Excel. This time, we will connect with Outlook.
Just like we have seen in the rest of the posts in the series, being able to connect with Outlook does not mean that it will be the best option for our project. In particular, there are better ways to establish communication, and even to send emails than using the Outlook API.
But in certain occasions, it is a project requirement to specifically do it in Outlook. For example, if we want to display the Outlook screen with the email generated before sending it, or if we want to add an appointment to a calendar.
In any case, it is a very interesting example of API usage and technology integration, which is the objective of this series. So, let’s get to it!
How to connect to Microsoft Outlook with a NET6 application
We start the example by creating a simple console application in NET6. We add as a reference ‘COM’ the “Microsoft Outlook xx.0 Object Library” reference, where xx will be the version of Microsoft Outlook installed on your computer.
In the case of Microsoft Outlook, we need to do a step that we did not have in Word and Excel, which is to allow access through programming. To do this, we enable the option in Options -> Trust Center -> Programmatic Access.
Next, we paste this code into our console application,
using Microsoft.Office.Interop.Outlook;
using OutlookApp = Microsoft.Office.Interop.Outlook.Application;
OutlookApp outlookApp = new OutlookApp();
MailItem mailItem = outlookApp.CreateItem(OlItemType.olMailItem);
mailItem.To = "your@email.com";
mailItem.Subject = $"Subject";
mailItem.HTMLBody = "";
mailItem.Display(false);
mailItem.Send();
Console.ReadLine();
The Microsoft Outlook documentation is not as good as that of Excel and Word, but I leave you a link in case of Visual Basic https://learn.microsoft.com/es-es/office/vba/outlook/concepts/getting-started/automating-outlook-from-a-visual-basic-application. It is not too difficult to translate the concepts.
With the .NET API for Microsoft Outlook, we can check received emails, create new emails, attach files, check the calendar, create new appointments, and in general, any option that we could do manually.
And that’s it for the part of the series dedicated to Microsoft Office applications. In the next post in the series, we will move on to CAD applications, looking at the Solid Works API.
Download the code
All the code from this post is available for download on Github.