Search code examples
c#outlookcastingcom-interopoffice-automation

Save outlook sent mail folder in sql


I'm trying to save out sent mail folder data in sql however I'm getting cast com object of type error/ I tried to online repair the Microsoft app and nothing happens.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection; // to use Missing.Value
//using Microsoft.Office.Interop.Outlook;
using System.Data.SqlClient;
using System.Data;
using Outlook = Microsoft.Office.Interop.Outlook;


namespace RetrieveEmail
{
    public class Program
    {
         static void Main(string[] args)
        {
            Outlook.Application oLk = new Outlook.Application();
            Outlook._NameSpace olNS = oLk.GetNamespace("MAPI");
            
            Outlook.MAPIFolder oFolderIn = olNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail);



            Outlook.Items oItems = oFolderIn.Items;

            foreach (Outlook.MailItem oMailItem in oFolderIn.Items)
            {
                if (oMailItem.SenderName != null)
                {

                    SqlConnection con = new SqlConnection(@"Data Source=\SQLEXPRESS; initial catalog=EmailReply;Integrated Security=True");
                 
                    SqlCommand cmd = new SqlCommand("INSERT INTO Emails (SenderName, Subject, Body) VALUES (@SenderName, @Subject, @Body)", con);
                    //cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@SenderName", oMailItem.SenderName);
                    cmd.Parameters.AddWithValue("@Subject", oMailItem.Subject);
                    cmd.Parameters.AddWithValue("@Body", oMailItem.Body);
                    //cmd.ExecuteNonQuery();

                    con.Open();
                    int k = cmd.ExecuteNonQuery();
                    if (k != 0)
                    {
                        Console.WriteLine("Record Inserted Succesfully into the Database");

                    }
                    con.Close();
                }
            }
        }
    }
}

Error:

System.InvalidCastException: 'Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Outlook.MailItem'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{00063034-0000-0000-C000-000000000046}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).'

enter image description here


Solution

  • You can have item types other than MailItem in the Sent Items folder - most likely you also have MeetingItem objects.

    foreach (object item in oFolderIn.Items)
    {
      if (item is Outlook.MailItem oMailItem)
      {
          ...
      }
    }