I am able to send the mail using below code:
private void btn_Send_Click(object sender, EventArgs e)
{
try
{
Outlook._Application _app = new Outlook.Application();
Outlook.MailItem mail = (Outlook.MailItem)_app.CreateItem(Outlook.OlItemType.olMailItem);
mail.To = txt_To.Text;
mail.Subject = txt_Subject.Text;
mail.Body = txt_Message.Text;
mail.Importance = Outlook.OlImportance.olImportanceNormal;
((Outlook._MailItem)mail).Send();
MessageBox.Show("Your Message has been successfully sent.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
But i am facing an error while reading the mails from outlook, below is my code to read the mail:
private void btn_Receive_Click(object sender, EventArgs e)
{
try
{
Outlook._Application _app = new Outlook.Application();
Outlook._NameSpace _ns = _app.GetNamespace("MAPI");
Outlook.MAPIFolder inbox = _ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
_ns.SendAndReceive(true);
dt = new DataTable("Inbox");
dt.Columns.Add("Subject", typeof(string));
dt.Columns.Add("Sender", typeof(string));
dt.Columns.Add("Body", typeof(string));
dt.Columns.Add("Date", typeof(string));
dataGrid.DataSource = dt;
foreach (Outlook.MailItem item in inbox.Items)
{
dt.Rows.Add(new object[] { item.Subject, item.SenderName, item.HTMLBody, item.SentOn.ToLongDateString() + "" + item.SentOn.ToLongDateString() });
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Error is: 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: 0*80004002 (E_NOINTERFACE)).
What I have tried:
After googling i found that we have to check If Item.Class=43, but when I try putting that If like: (if(item.Class=43)) condition, it shows a error stating
Property or indexer '_MailItem.Class' cannot be assigned to -- it is read only
Kindly help me to fix this.