Save outlook sent mail folder in sql

Joined
Feb 2, 2022
Messages
15
Programming Experience
Beginner
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.

C#:
 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=TCLS-DT0052\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)).'

1644888270545.png
 
Not all items in a folder will be a MailItem. You have to be able to handle those cases (or manually scrub the folders so that they only contain MailItems).
 

Latest posts

Back
Top Bottom