Saturday, March 21, 2015

Send mail using Outlook and .oft templates

There is already a page for sending mail using Outlook library.
Now this small code is a small tweak i.e. using Outlook Template (*.oft) file.

If you see the code there is hardly any complication but this exercise is time consuming as a whole.
It is because defining the different mail templates takes a lot of time from business POV.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Outlook = Microsoft.Office.Interop.Outlook;

namespace emailTemplateTest {
 class Program {
  static void Main(string[] args) {
   try {
    Outlook.Application otApp = new Outlook.Application(); // create outlook object
    Outlook.NameSpace ns = otApp.Session;
    Outlook.Folder folder = otApp.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderDrafts) as Outlook.Folder;
    Outlook.MailItem otMsg = otApp.CreateItemFromTemplate(@ "d:\a2.oft", folder) as Outlook.MailItem; // Open the mail template
    Outlook.Inspector oInspector = otMsg.GetInspector;
    Outlook.Recipient otRecip = (Outlook.Recipient) otMsg.Recipients.Add("Temp@hotmail.com");
    if (otRecip.Resolve()) // validate recipient address
    {
     // Modify the body text as required
     otMsg.Send(); // Send Mail
     otRecip = null;
     otMsg = null;
     otApp.Quit();
    }
   } catch (Exception e) {
    Console.WriteLine("{0} Exception caught: ", e);
   }
  }
 }
}