Attention, Folder RetrieveMail is inside Inbox, it is not a main folder
Save Outlook email Information to SQL Server
0
I'm trying to save inbound Outlook mail data to sql server however I'm getting in error in System.Runtime.InteropServices.COMException: 'The attempted operation failed. An object could not be found.' What did I missed
Note: RetrieveMail is exist in mailbox
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._Folders oFolders;
oFolders = olNS.Folders;
Outlook.MAPIFolder oFolder;
oFolder = oFolders[1];
Outlook.MAPIFolder oFolderIn = oFolder.Folders["RetrieveMail"];
Outlook.Items oItems = oFolderIn.Items;
foreach (Outlook.MailItem oMailItem in oFolderIn.Items)
{
if (oMailItem.SenderName == "sender_name")
{
SqlConnection con = new SqlConnection(@"Data Source=TCLS-DT0052\SQLEXPRESS; initial catalog=EmailReply;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand("Emails", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("Subject", oMailItem.Subject);
cmd.Parameters.AddWithValue("Body", oMailItem.Body);
con.Open();
int k = cmd.ExecuteNonQuery();
if (k != 0)
{
Console.WriteLine("Record Inserted Succesfully into the Database");
}
con.Close();
}
}
}
}
}
Outlook | Windows | Classic Outlook for Windows | For business
Developer technologies | C#
2 answers
Sort by: Most helpful
-
-
Jack J Jun 25,296 Reputation points
2022-02-10T02:30:54.297+00:00 @ika palad , you could try the following code to access custom folder in Outlook.
Outlook.Application oLk = new Outlook.Application(); Outlook.MAPIFolder rootFolder = oLk.Session.DefaultStore.GetRootFolder(); Outlook.MAPIFolder folder =rootFolder.Folders["Retieve"]; Console.WriteLine(folder.Items.Count);
I can get the count number is 1.(This is correct for my situation)
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.