Search code examples
c#outlookoffice-interop

How do I create an Outlook MailItem in .NET 3.5?


I have the following code that I have built in .Net 4.0, It works fine, but I now have to build the project in .Net 3.5 and I'm getting an error when creating the MailItem. The error message is :-

"'cannot implicitly convert type 'object' to 'microsoft.office.interop.outlook.olmailitem'"

 Outlook.Application application = new Outlook.Application();

    Outlook.Folder folder = 


        application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderDrafts) 
                        as Outlook.Folder;

    Outlook.MailItem mail =
                    application.CreateItem(Outlook.OlItemType.olMailItem);

    foreach (string name in addlist)
                {
                    mail.Recipients.Add(name);
                }

    mail.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
                mail.HTMLBody = msg;
                mail.Subject = textBox1.Text;
                mail.Save();

Can anyone help? I'm struggling to resovle the syntax issue?


Solution

  • Outlook.Application.CreateItem returns an object (dynamic, to be accurate), you have to explicitly cast it to Outlook.MailItem, like this:

    Outlook.MailItem mail = 
                    application.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem;