Error while reading inbox items from outlook using C# - c#

HI
When i am trying to read data from inbox of outlook , i am getting the below error
Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Outlook.PostItem'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{00063024-0000-0000-C000-000000000046}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).
Below is my C# code
Microsoft.Office.Interop.Outlook.Application app = null;
Microsoft.Office.Interop.Outlook._NameSpace ns = null;
Microsoft.Office.Interop.Outlook.PostItem item = null;
Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null;
Microsoft.Office.Interop.Outlook.MAPIFolder subFolder = null;
try
{
app = new Microsoft.Office.Interop.Outlook.Application();
ns = app.GetNamespace("MAPI");
ns.Logon(null,null,false, false);
inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
Console.WriteLine("Folder Name: {0}, EntryId: {1}", inboxFolder.Name, inboxFolder.EntryID);
Console.WriteLine("Num Items: {0}", inboxFolder.Items.Count.ToString());
Console.ReadLine();
for (int i = 1; i <= inboxFolder.Items.Count; i++)
{
item = (Microsoft.Office.Interop.Outlook.PostItem)inboxFolder.Items[i];
Console.WriteLine("Item: {0}", i.ToString());
Console.WriteLine("Subject: {0}", item.Subject);
Console.WriteLine("Categories: {0}", item.Categories);
Console.WriteLine("Body: {0}", item.Body);
Console.WriteLine("HTMLBody: {0}", item.HTMLBody);
}
}
catch (System.Runtime.InteropServices.COMException ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
ns = null;
app = null;
inboxFolder = null;
}
Thanks in Advance

item = (Microsoft.Office.Interop.Outlook.PostItem)inboxFolder.Items[i];
Console.WriteLine("Item: {0}", i.ToString());
Console.WriteLine("Subject: {0}", item.Subject);
Console.WriteLine("Categories: {0}", item.Categories);
Console.WriteLine("Body: {0}", item.Body);
Console.WriteLine("HTMLBody: {0}", item.HTMLBody);
Change this part as
Microsoft.Office.Interop.Outlook.MailItem item = (Microsoft.Office.Interop.Outlook.MailItem)subFolder.Items[i];
Console.WriteLine( "Item: {0}", i.ToString() );
Console.WriteLine( "Subject: {0}", item.Subject );
Console.WriteLine( "Categories: {0}", item.Categories );
Console.WriteLine( "Body: {0}", item.Body );
Console.WriteLine( "HTMLBody: {0}", item.HTMLBody );
further refer
http://www.dotnetspider.com/forum/160348-how-read-items-from-outlook-inbox-subfolders-C-NET.aspx

Related

how to update POP3 server in C#

I'm trying to retrieve data from email and then work with it. Everything is fine, I can get the data, but I need to get the most recent ones. When I run this code and send an email in the process, it doesn't come up until I turn it on. I have tried turning the SSL connection or client to the server on and off and back on again (like some kind of update, but with the same result).
Thanks for any reaction or ideas. :)
using EAGetMail;
using System;
using System.Globalization;
using System.IO;
namespace PopServer
{
class Program
{
static string _generateFileName(int sequence)
{
DateTime currentDateTime = DateTime.Now;
return string.Format("{0}-{1:000}-{2:000}.eml",
currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")),
currentDateTime.Millisecond,
sequence);
}
static void Main(string[] args)
{
try
{
string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
MailServer oServer = new MailServer("popserver.com",
"username#mail.com",
"password",
ServerProtocol.Pop3);
oServer.SSLConnection = true;
oServer.Port = 995;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} email(s)\r\n", infos.Length);
//Here I tried to take advantage of the fact that if the application is connected via SSLConnection, it could update, but it only prints the emails before starting the application
while (oServer.SSLConnection)
{
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);
Mail oMail = oClient.GetMail(info);
Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
Console.WriteLine("Body: {0}\r\n", oMail.TextBody);
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
oMail.SaveAs(fullPath, true);
//Delete email-isRead
//oClient.Delete(info);
}
}
oClient.Quit();
Console.WriteLine("Completed!");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
try
{
bool help = true;
do{
string localInbox = string.Format("{0}\\inbox",
Directory.GetCurrentDirectory());
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
MailServer oServer = new MailServer("popserver.com",
"username#mail.com",
"password",
ServerProtocol.Pop3);
oServer.SSLConnection = true;
oServer.Port = 995;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} email(s)\r\n", infos.Length);
//Here I tried to take advantage of the fact that if the application is connected via SSLConnection, it could update, but it only prints the emails before starting the application
while (oServer.SSLConnection)
{
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);
Mail oMail = oClient.GetMail(info);
Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
Console.WriteLine("Body: {0}\r\n", oMail.TextBody);
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
oMail.SaveAs(fullPath, true);
//Delete email-isRead
//oClient.Delete(info);
}
}
Console.WriteLine("Again?");
Console.WriteLine("1-y");
Console.WriteLine("2-n");
int a = Convert.ToInt32(Console.ReadLine());
if (a == 2)
{
help = false;
}
//Just easily restarted hole code
while(help != false)
oClient.Quit();
Console.WriteLine("Completed!");

C# runs Powershell with Get-MpThreatDetection

If you run the command "Get-MpThreatDetection" in the powershell console you get (if any threats was found in the past) 17 Attributes shown in the console. But now I try the same command on a c# app, I get only the DetectionID and the ThreatID. If I try the same thing with the "help" command, I get the exact same Output on both ways.
But why?
C# Code:
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript("Get-MpThreatDetection");
Collection<PSObject> result = PowerShellInstance.Invoke();
foreach (PSObject r in result)
{
PSResult.Add(r.BaseObject.ToString());
}
}
(If you want to make a test threat to get something back with this command, save a Textfile with the Code in this link.)
Output from Powershell:
Powershell Output Image
Output from the Code:
MSFT_MpThreatDetection (DetectionID = "{E186D279-4BA0-4FA5-8CD2-84F2D053CA6D}", ThreatID = 2147519003)
Here is an Answere even without powershell.
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\Microsoft\\Windows\\Defender",
"SELECT * FROM MSFT_MpThreatDetection");
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("MSFT_MpThreatDetection instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("ActionSuccess: {0}", queryObj["ActionSuccess"]);
Console.WriteLine("AdditionalActionsBitMask: {0}", queryObj["AdditionalActionsBitMask"]);
Console.WriteLine("AMProductVersion: {0}", queryObj["AMProductVersion"]);
Console.WriteLine("CleaningActionID: {0}", queryObj["CleaningActionID"]);
Console.WriteLine("CurrentThreatExecutionStatusID: {0}", queryObj["CurrentThreatExecutionStatusID"]);
Console.WriteLine("DetectionID: {0}", queryObj["DetectionID"]);
Console.WriteLine("DetectionSourceTypeID: {0}", queryObj["DetectionSourceTypeID"]);
Console.WriteLine("DomainUser: {0}", queryObj["DomainUser"]);
Console.WriteLine("InitialDetectionTime: {0}", queryObj["InitialDetectionTime"]);
Console.WriteLine("LastThreatStatusChangeTime: {0}", queryObj["LastThreatStatusChangeTime"]);
Console.WriteLine("ProcessName: {0}", queryObj["ProcessName"]);
Console.WriteLine("RemediationTime: {0}", queryObj["RemediationTime"]);
if(queryObj["Resources"] == null)
Console.WriteLine("Resources: {0}", queryObj["Resources"]);
else
{
String[] arrResources = (String[])(queryObj["Resources"]);
foreach (String arrValue in arrResources)
{
Console.WriteLine("Resources: {0}", arrValue);
}
}
Console.WriteLine("ThreatID: {0}", queryObj["ThreatID"]);
Console.WriteLine("ThreatStatusErrorCode: {0}", queryObj["ThreatStatusErrorCode"]);
Console.WriteLine("ThreatStatusID: {0}", queryObj["ThreatStatusID"]);
}

Active directory time out exception due to searchresultcollection object count

i am facing the issue while searching the group name in active directory,
below link is related to my error but it doesn't solved my issue
DirectorySearcher FindAll SearchResultCollection Count throws COMException
string search = "*" + txtsearch.Text + "*";
if (string.IsNullOrEmpty(txtsearch.Text))
{
search = "*";
}
DirectoryEntry de = null;
try
{
de = new DirectoryEntry(strADPath,strUsreName,strUsrePassword);
}
catch (Exception ex)
{
LogMessageToFile("Fail to set the data for the DirectoryEntry : " + ex.ToString()+ "....Error message"+ ex.Message);
}
DirectorySearcher deSearch = new DirectorySearcher();
deSearch.PropertiesToLoad.Add("objectguid");
deSearch.PropertiesToLoad.Add("cn");
deSearch.SearchRoot = de;
try
{
deSearch.PropertiesToLoad.Add("cn"); deSearch.Filter = "(&(objectClass=group)(cn=" + search + "))";
}
catch (Exception ex)
{
LogMessageToFile("error while passing value to filter value" + ex.ToString()+"....Error message"+ ex.Message);
}
SearchResultCollection results= null;
try
{
results = deSearch.FindAll();
}
catch (Exception ex)
{
LogMessageToFile("Fail to FindAll method :" + ex.ToString() + "....Error message" + ex.Message);
}
DataTable tbGroup = dsGroup.Tables.Add("Groups");
tbGroup.Columns.Add("GroupName");
tbGroup.Columns.Add("GroupGuid");
if (results != null)
{
if (results.Count > 0)
{
foreach (SearchResult Result in results)
{
DataRow rwGroup = tbGroup.NewRow();
try
{
if (Result.Properties["cn"] != null)
{
if (Result.Properties["cn"].Count > 0)
{
rwGroup["GroupName"] = Result.Properties["cn"][0];
}
else
{
LogMessageToFile("Result.Properties count less then 0");
}
}
}
catch (Exception ex)
{
LogMessageToFile("try to obtain Result.Properties :" + ex.ToString() + "....Error message" + ex.Message);
}
try
{
rwGroup["GroupGuid"] = GetObjectIdetifier(Result);
}
catch (Exception ex)
{
LogMessageToFile("Fail to get the data for GroupGuid :" + ex.ToString()+"....Error message" + ex.Message);
}
tbGroup.Rows.Add(rwGroup);
}
listBox1.DataSource = tbGroup;
listBox1.DisplayMember = "GroupName";
listBox1.ValueMember = "GroupGuid";
}
}

How do I parse ms outlook 2003 email body for a string i.e. keyword 'error'

I am trying to figure out how to parse ms outlook 2003 email body for a string using C# eg: read all the email in certain folder and search the email body for the word "error" in these emails.
Once this string error is found in the email body I would like to display the email and the error message.
I have the following code so far which basically just reads all the emails in the folder and displays all the information about the emails.
The issue I am having is actually trying to read into the mail item body in each individual email so I can search for the string.
I have been searching quite a while for this on web and have found code very similar to what I have below but none which shows you or if it is possible to read a folder containing emails, read through individual each email and search for the string 'errors', if this keyword is found in the email display the details from email i.e email subject, error message etc.
Any help would be much appreciated.
Thanks a million.
John.
using System;
using System.Reflection;
using Outlook = Microsoft.Office.Interop.Outlook;
namespace AccessOutlook
{
public class Class1
{
public static void Main(string[] args)
{
Microsoft.Office.Interop.Outlook.Application app = null;
Microsoft.Office.Interop.Outlook._NameSpace ns = null;
Microsoft.Office.Interop.Outlook.MailItem item = null;
Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null;
Microsoft.Office.Interop.Outlook.MAPIFolder subFolder = null;
try
{
app = new Microsoft.Office.Interop.Outlook.Application();
ns = app.GetNamespace("MAPI");
ns.Logon(null,null,false, false);
inboxFolder = ns.GetDefaultFolder
(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
subFolder = inboxFolder.Folders["Docs"];
Console.WriteLine("Folder Name: {0}, EntryId: {1}", subFolder.Name,
subFolder.EntryID);
Console.WriteLine("Num Items: {0}",
subFolder.Items.Count.ToString());
for(int i=1;i<=subFolder.Items.Count;i++)
{
item =
(Microsoft.Office.Interop.Outlook.MailItem)subFolder.Items[i];
Console.WriteLine("Item: {0}", i.ToString());
Console.WriteLine("Subject: {0}", item.Subject);
Console.WriteLine("Sent: {0} {1}",
item.SentOn.ToLongDateString(), item.SentOn.ToLongTimeString());
Console.WriteLine("Categories: {0}", item.Categories);
Console.WriteLine("Body: {0}", item.Body);
Console.WriteLine("HTMLBody: {0}", item.HTMLBody);
}
}
catch (System.Runtime.InteropServices.COMException ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
ns = null;
app = null;
inboxFolder = null;
}
}
}
}
How about this:
for(int i=1;i<=subFolder.Items.Count;i++)
{
item = (Microsoft.Office.Interop.Outlook.MailItem)subFolder.Items[i];
if(item.Body.Contains("errors"))
{
Console.WriteLine("Item: {0}", i.ToString());
Console.WriteLine("Subject: {0}", item.Subject);
Console.WriteLine("Sent: {0} {1}",
item.SentOn.ToLongDateString(), item.SentOn.ToLongTimeString());
Console.WriteLine("Categories: {0}", item.Categories);
Console.WriteLine("Body: {0}", item.Body);
Console.WriteLine("HTMLBody: {0}", item.HTMLBody);
}
}

Parsing emails in outloook with C#

I'm writing a program to read all my outlook emails, eventually the search will be more specific but for now i want to read all the email in my inbox. i have code running that reads what i want up to 169 for some reason...
namespace reademail
{
static class Program
{
public static Microsoft.Office.Interop.Outlook.Application myApp;
public static void Main(string[] args)
{
// myApp = new Microsoft.Office.Interop.Outlook.Application();
//myApp.NewMailEx += new Microsoft.Office.Interop.Outlook.ApplicationEvents_11_NewMailExEventHandler(OutlookNewMailReceived);
ReadMail();
}
static void ReadMail()
{
Microsoft.Office.Interop.Outlook.Application app = null;
Microsoft.Office.Interop.Outlook._NameSpace ns = null;
Microsoft.Office.Interop.Outlook.MailItem item = null;
Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null;
app = new Microsoft.Office.Interop.Outlook.Application();
ns = app.GetNamespace("MAPI");
//ns.Logon(null, null, false, false);
inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
// subFolder = inboxFolder.Folders["Inbox"]; //folder.Folders[1]; also works
Console.WriteLine("Folder Name: {0}, EntryId: {1}", inboxFolder.Name, inboxFolder.EntryID);
Console.WriteLine("Num Items: {0}", inboxFolder.Items.Count.ToString());
//System.IO.StreamWriter strm = new System.IO.StreamWriter("C:/Test/Inbox.txt");
for (int counter = 1; counter <= inboxFolder.Items.Count; counter++)
{
Console.Write(inboxFolder.Items.Count + " " + counter);
item = (Microsoft.Office.Interop.Outlook.MailItem)inboxFolder.Items[counter];
Console.WriteLine("Item: {0}", counter.ToString());
Console.WriteLine("Subject: {0}", item.Subject);
Console.WriteLine("Sent: {0} {1}", item.SentOn.ToLongDateString(), item.SentOn.ToLongTimeString());
Console.WriteLine("Sendername: {0}", item.SenderName);
Console.WriteLine("Body: {0}", item.Body);
//strm.WriteLine(counter.ToString() + "," + item.Subject + "," + item.SentOn.ToShortDateString() + "," + item.SenderName);
}
//strm.Close();
}
}
}
The loop reads up to 169 emails and then crashes, also it starts reading emails at what seems to be an arbitrary date...I'm not sure whats preventing it from reading all emails...
Folder Name: Inbox, EntryId: 000000003527EA8DB4FFC04EB6ABA4DE31CB4BA40100C6D3EBA
DBDB57E438D0B53C5FB515CC50000660627C70000
Num Items: 1048
System.InvalidCastException: Unable to cast COM object of type 'System.__ComObje
ct' to interface type 'Microsoft.Office.Interop.Outlook.MailItem'. This operatio
n failed because the QueryInterface call on the COM component for the interface
with IID '{00063034-0000-0000-C000-000000000046}' failed due to the following er
ror: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERF
ACE)).
at CallSite.Target(Closure , CallSite , Object )
at reademail.Program.ReadMail() in C:\Documents and Settings\DBubel\my docume
nts\visual studio 2010\Projects\reademail\reademail\Program.cs:line 60
Press any key to continue . . .
My guess is that you have items in your inbox that do not apply the Microsoft.Office.Interop.Outlook.MailItem interface and therefore the code crashes while going through the loop and attempting to cast. One possible workaround, if you are using .NET4 since it has support for dynamic, is not to cast the object but rather pass it to a dynamic variable.
dynamic item = inboxFolder.Items[counter];
This worked for me as your code was having problems handling meeting invites in the inbox folder.
Full modified code:
namespace reademail
{
static class Program
{
public static Microsoft.Office.Interop.Outlook.Application myApp;
public static void Main(string[] args)
{
// myApp = new Microsoft.Office.Interop.Outlook.Application();
//myApp.NewMailEx += new Microsoft.Office.Interop.Outlook.ApplicationEvents_11_NewMailExEventHandler(OutlookNewMailReceived);
ReadMail();
}
static void ReadMail()
{
Microsoft.Office.Interop.Outlook.Application app = null;
Microsoft.Office.Interop.Outlook._NameSpace ns = null;
//Microsoft.Office.Interop.Outlook.MailItem item = null;
Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null;
app = new Microsoft.Office.Interop.Outlook.Application();
ns = app.GetNamespace("MAPI");
//ns.Logon(null, null, false, false);
inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
// subFolder = inboxFolder.Folders["Inbox"]; //folder.Folders[1]; also works
Console.WriteLine("Folder Name: {0}, EntryId: {1}", inboxFolder.Name, inboxFolder.EntryID);
Console.WriteLine("Num Items: {0}", inboxFolder.Items.Count.ToString());
//System.IO.StreamWriter strm = new System.IO.StreamWriter("C:/Test/Inbox.txt");
for (int counter = 1; counter <= inboxFolder.Items.Count; counter++)
{
Console.Write(inboxFolder.Items.Count + " " + counter);
dynamic item = inboxFolder.Items[counter];
//item = (Microsoft.Office.Interop.Outlook.MailItem)inboxFolder.Items[counter];
Console.WriteLine("Item: {0}", counter.ToString());
Console.WriteLine("Subject: {0}", item.Subject);
Console.WriteLine("Sent: {0} {1}", item.SentOn.ToLongDateString(), item.SentOn.ToLongTimeString());
Console.WriteLine("Sendername: {0}", item.SenderName);
Console.WriteLine("Body: {0}", item.Body);
//strm.WriteLine(counter.ToString() + "," + item.Subject + "," + item.SentOn.ToShortDateString() + "," + item.SenderName);
}
//strm.Close();
}
}
}
If you want only MailItems then you should check that the item you retrieve is a valid MailItem instead of assuming you have one. It could be CalendarItem, DocumentItem, etc. which varies by olItemType. Your current code explicitly assumes you only have MailItems in your inbox.
item = inboxFolder.Items[counter] as Microsoft.Office.Interop.Outlook.MailItem;
if (item != null)
{
....
}
Your error indicates that you may have a MailItem - but it could be a Mail Delivery Report (Read Receipt, etc.). See this post for reference with the casting error. They suggest leveraging the Outlook Table interface as a workaround and checking the object Class. This may be another option for you.

Categories

Resources