Reputation: 1
i am working on a code that get's a list and checks if the items is in emails subjects, i am trying to go through all the emails to compare to the list but the program crashes after 190 emails or so (there are 289 emails in the folder)
I searched online for solutions for this problem and nothing worked for me
oApp = new Microsoft.Office.Interop.Outlook.Application();
// Get the MAPI namespace.
oNS = oApp.GetNamespace("mapi");
// Log on by using the default profile or existing session (no dialog box).
oNS.Logon(Missing.Value, Missing.Value, false, true);
// Alternate logon method that uses a specific profile name.
// TODO: If you use this logon method, specify the correct profile name
// and comment the previous Logon line.
//oNS.Logon("profilename",Missing.Value,false,true);
//Get the Inbox folder.
oInbox = oNS.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
//Get the Items collection in the Inbox folder.
oItems = oInbox.Items;
MessageBox.Show(oItems.Count+"");
oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oItems.GetLast();
public void SearchEmail()
{
if (counter<oItems.Count)
{
try
{
string s;
if (oMsg != null)
{
s = oMsg.Subject;
for (int i = 0; i < allTickets.Count; i++)
{
label2.Text = oMsg.Subject;
string ticketID = allTickets[i].ToString();
if (s.Contains(ticketID) && oMsg.UnRead)
{
unreadTickets.Add(ticketID);
}
}
}
oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oItems.GetPrevious();
counter++;
button2.Text = counter + "";
}
//Error handler.
catch (Exception x)
{
//MessageBox.Show(x.ToString());
}
}
}
the catch exception gives me this:
unable to cast com object of type 'system.__comobject' to interface type 'microsoft.office.interop.outlook
and afterward i am getting this error:
nullreferenceexception object reference not set to an instance of an object
Upvotes: 0
Views: 72
Reputation: 66215
Keep in mind that Inbox can contain items other than MailItem
, such as ReportItem
or MeetingItem
. That would explain the cast error. You need to treat items as a generic object and read the Class
property (exposed by all OOM objects) using reflection - if it is 43 (olMailItem
), you can cast it to MailItem
. Or you can use the "as" operator and check for null.
Also keep in mind that the Items collection is not sorted in any particular order unless you first call Items.Sort
and specify a sort order; otheriwise what you get from Items.GetLast
is undetermined.
Upvotes: 1