Tuesday, November 11, 2008

Fun with Outlook and .NET

You need to add reference to Microsoft.Office.Interop.Outlook.

Reading email in 11 lines of code:

using Microsoft.Office.Interop.Outlook;
...
Application Outlook = new Application();
NameSpace OutlookNs = Outlook.GetNamespace("MAPI");
OutlookNs.Logon(null, null, true, true);
Folder inbox =
(Folder)Outlook.Session.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
Folder destination = GetDestinationFolder();
foreach (object item in inbox.Items)
{
if (item is MailItem)
{
MailItem mail = (MailItem)item;
Console.Write(mail.SenderName + ": " + mail.Subject);
}
}
OutlookNs.Logoff();

Sending email in 12 lines of code:

using Microsoft.Office.Interop.Outlook;
...
Application Outlook = new Application();
NameSpace OutlookNs = Outlook.GetNamespace("MAPI");
OutlookNs.Logon(null, null, true, true);
MailItem mail = (MailItem)OutlookNs.Application.CreateItem(OlItemType.olMailItem);
mail.BodyFormat = OlBodyFormat.olFormatPlain;
mail.Body = "Hello, world!";
mail.Subject = "Sent from C# code snippet!";
mail.Recipients.Add("alias");
mail.Recipients.ResolveAll();
mail.Send();
OutlookNs.Logoff();

No comments: