您好我需要提取未读电子邮件。最后几行是否正确,因为当i
为0时抛出异常 - 数组索引超出范围。
Microsoft.Office.Interop.Outlook.Application myApp = new Microsoft.Office.Interop.Outlook.ApplicationClass();
Microsoft.Office.Interop.Outlook.NameSpace mapiNameSpace = myApp.GetNamespace("MAPI");
Microsoft.Office.Interop.Outlook.MAPIFolder myInbox = mapiNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
Microsoft.Office.Interop.Outlook.Items oItems = myInbox.Items.Restrict("[UnRead] = true");
for(int i = 0; i <= oItems.Count; i++)
{
Microsoft.Office.Interop.Outlook.MailItem oMsg = ( Microsoft.Office.Interop.Outlook.MailItem)oItems[i];
textEmail.Text += "\r\nSubject:" + oMsg.Subject.ToString();
}
答案 0 :(得分:2)
Microsoft.Office.Interop.Outlook.Items集合的索引从1开始(可能是由于Exchange对象的遗留+ VBA影响)
因此,您需要从1启动计数器或使用for each循环。 (也是你的结束索引检查错误)
// index starts from 1.
for(int i = 1; i <= oItems.Count; i++)
{
Microsoft.Office.Interop.Outlook.MailItem oMsg = ( Microsoft.Office.Interop.Outlook.MailItem)oItems[i];
textEmail.Text += "\r\nSubject:" + oMsg.Subject.ToString();
}
另一种选择是使用比for循环稍慢的foreach循环,但是对于所有实际目的而言几乎等效。
// var doesn't work for these com based legacy object models.
foreach(Microsoft.Office.Interop.Outlook.MailItem oMsg in oItems)
{
textEmail.Text += "\r\nSubject:" + oMsg.Subject.ToString();
}
答案 1 :(得分:1)
尝试使用foreach循环
foreach (var item in oItems)
{
textEmail.Text += "\r\nSubject:" + item.Subject.ToString();
}
...