How can I get all items from a specific calendar (for a specific date).
Lets say for instance that I have a calendar with a recurring item every Monday evening. When I request all items like this:
CalendarItems = CalendarFolder.Items;
CalendarItems.IncludeRecurrences = true;
I only get 1 item...
Is there an easy way to get all items (main item + derived items) from a calendar?
In my specific situation it can be possible to set a date limit but it would be cool just to get all items (my recurring items are time limited themselves).
I'm using the Microsoft Outlook 12 Object library (Microsoft.Office.Interop.Outlook).
I've studied the docs and this is my result:
I've put a time limit of one month hard-coded, but this is just an example.
public void GetAllCalendarItems()
{
Microsoft.Office.Interop.Outlook.Application oApp = null;
Microsoft.Office.Interop.Outlook.NameSpace mapiNamespace = null;
Microsoft.Office.Interop.Outlook.MAPIFolder CalendarFolder = null;
Microsoft.Office.Interop.Outlook.Items outlookCalendarItems = null;
oApp = new Microsoft.Office.Interop.Outlook.Application();
mapiNamespace = oApp.GetNamespace("MAPI"); ;
CalendarFolder = mapiNamespace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar);
outlookCalendarItems = CalendarFolder.Items;
outlookCalendarItems.IncludeRecurrences = true;
foreach (Microsoft.Office.Interop.Outlook.AppointmentItem item in outlookCalendarItems)
{
if (item.IsRecurring)
{
Microsoft.Office.Interop.Outlook.RecurrencePattern rp = item.GetRecurrencePattern();
DateTime first = new DateTime(2008, 8, 31, item.Start.Hour, item.Start.Minute, 0);
DateTime last = new DateTime(2008, 10, 1);
Microsoft.Office.Interop.Outlook.AppointmentItem recur = null;
for (DateTime cur = first; cur <= last; cur = cur.AddDays(1))
{
try
{
recur = rp.GetOccurrence(cur);
MessageBox.Show(recur.Subject + " -> " + cur.ToLongDateString());
}
catch
{ }
}
}
else
{
MessageBox.Show(item.Subject + " -> " + item.Start.ToLongDateString());
}
}
}
I believe that you must Restrict or Find in order to get recurring appointments, otherwise Outlook won't expand them. Also, you must Sort by Start before setting IncludeRecurrences.
I wrote similar code, but then found the export functionality:
Application outlook;
NameSpace OutlookNS;
outlook = new ApplicationClass();
OutlookNS = outlook.GetNamespace("MAPI");
MAPIFolder f = OutlookNS.GetDefaultFolder(OlDefaultFolders.olFolderCalendar);
CalendarSharing cs = f.GetCalendarExporter();
cs.CalendarDetail = OlCalendarDetail.olFullDetails;
cs.StartDate = new DateTime(2011, 11, 1);
cs.EndDate = new DateTime(2011, 12, 31);
cs.SaveAsICal("c:\\temp\\cal.ics");
LinqPad snipped that works for me:
//using Microsoft.Office.Interop.Outlook
Application a = new Application();
Items i = a.Session.GetDefaultFolder(OlDefaultFolders.olFolderCalendar).Items;
i.IncludeRecurrences = true;
i.Sort("[Start]");
i = i.Restrict(
"[Start] >= '10/1/2013 12:00 AM' AND [End] < '10/3/2013 12:00 AM'");
var r =
from ai in i.Cast<AppointmentItem>()
select new {
ai.Categories,
ai.Start,
ai.Duration
};
r.Dump();
If you need want to access the shared folder from your friend, then you can set your friend as the recipient. Requirement: his calendar must be shared first.
// Set recepient
Outlook.Recipient oRecip = (Outlook.Recipient)oNS.CreateRecipient("abc#yourmail.com");
// Get calendar folder
Outlook.MAPIFolder oCalendar = oNS.GetSharedDefaultFolder(oRecip, Outlook.OlDefaultFolders.olFolderCalendar);
There is no need to expand recurring items manually. Just ensure you sort the items before using IncludeRecurrences.
Here is VBA example:
tdystart = VBA.Format(#8/1/2012#, "Short Date")
tdyend = VBA.Format(#8/31/2012#, "Short Date")
Dim folder As MAPIFolder
Set appointments = folder.Items
appointments.Sort "[Start]" ' <-- !!! Sort is a MUST
appointments.IncludeRecurrences = True ' <-- This will expand reccurent items
Set app = appointments.Find("[Start] >= """ & tdystart & """ and [Start] <= """ & tdyend & """")
While TypeName(app) <> "Nothing"
MsgBox app.Start & " " & app.Subject
Set app = appointments.FindNext
Wend
public void GetAllCalendarItems()
{
DataTable sample = new DataTable(); //Sample Data
sample.Columns.Add("Subject", typeof(string));
sample.Columns.Add("Location", typeof(string));
sample.Columns.Add("StartTime", typeof(DateTime));
sample.Columns.Add("EndTime", typeof(DateTime));
sample.Columns.Add("StartDate", typeof(DateTime));
sample.Columns.Add("EndDate", typeof(DateTime));
sample.Columns.Add("AllDayEvent", typeof(bool));
sample.Columns.Add("Body", typeof(string));
listViewContacts.Items.Clear();
oApp = new Outlook.Application();
oNS = oApp.GetNamespace("MAPI");
oCalenderFolder = oNS.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar);
outlookCalendarItems = oCalenderFolder.Items;
outlookCalendarItems.IncludeRecurrences = true;
// DataTable sample = new DataTable();
foreach (Microsoft.Office.Interop.Outlook.AppointmentItem item in outlookCalendarItems)
{
DataRow row = sample.NewRow();
row["Subject"] = item.Subject;
row["Location"] = item.Location;
row["StartTime"] = item.Start.TimeOfDay.ToString();
row["EndTime"] = item.End.TimeOfDay.ToString();
row["StartDate"] = item.Start.Date;
row["EndDate"] = item.End.Date;
row["AllDayEvent"] = item.AllDayEvent;
row["Body"] = item.Body;
sample.Rows.Add(row);
}
sample.AcceptChanges();
foreach (DataRow dr in sample.Rows)
{
ListViewItem lvi = new ListViewItem(dr["Subject"].ToString());
lvi.SubItems.Add(dr["Location"].ToString());
lvi.SubItems.Add(dr["StartTime"].ToString());
lvi.SubItems.Add(dr["EndTime"].ToString());
lvi.SubItems.Add(dr["StartDate"].ToString());
lvi.SubItems.Add(dr["EndDate"].ToString());
lvi.SubItems.Add(dr["AllDayEvent"].ToString());
lvi.SubItems.Add(dr["Body"].ToString());
this.listViewContacts.Items.Add(lvi);
}
oApp = null;
oNS = null;
}
I found this article very useful: https://learn.microsoft.com/en-us/office/client-developer/outlook/pia/how-to-search-and-obtain-appointments-in-a-time-range
It demonstrates how to get calendar entries in a specified time range. It worked for me. Here is the source code from the article for your convenience :)
using Outlook = Microsoft.Office.Interop.Outlook;
private void DemoAppointmentsInRange()
{
Outlook.Folder calFolder = Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar)
as Outlook.Folder;
DateTime start = DateTime.Now;
DateTime end = start.AddDays(5);
Outlook.Items rangeAppts = GetAppointmentsInRange(calFolder, start, end);
if (rangeAppts != null)
{
foreach (Outlook.AppointmentItem appt in rangeAppts)
{
Debug.WriteLine("Subject: " + appt.Subject
+ " Start: " + appt.Start.ToString("g"));
}
}
}
/// <summary>
/// Get recurring appointments in date range.
/// </summary>
/// <param name="folder"></param>
/// <param name="startTime"></param>
/// <param name="endTime"></param>
/// <returns>Outlook.Items</returns>
private Outlook.Items GetAppointmentsInRange(
Outlook.Folder folder, DateTime startTime, DateTime endTime)
{
string filter = "[Start] >= '"
+ startTime.ToString("g")
+ "' AND [End] <= '"
+ endTime.ToString("g") + "'";
Debug.WriteLine(filter);
try
{
Outlook.Items calItems = folder.Items;
calItems.IncludeRecurrences = true;
calItems.Sort("[Start]", Type.Missing);
Outlook.Items restrictItems = calItems.Restrict(filter);
if (restrictItems.Count > 0)
{
return restrictItems;
}
else
{
return null;
}
}
catch { return null; }
}
Try this:
public List<AdxCalendarItem> GetAllCalendarItems()
{
Outlook.Application OutlookApp = new Outlook.Application();
List<AdxCalendarItem> result = new List<AdxCalendarItem>();
Outlook._NameSpace session = OutlookApp.Session;
if (session != null)
try
{
object stores = session.GetType().InvokeMember("Stores", BindingFlags.GetProperty, null, session, null);
if (stores != null)
try
{
int count = (int)stores.GetType().InvokeMember("Count", BindingFlags.GetProperty, null, stores, null);
for (int i = 1; i <= count; i++)
{
object store = stores.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, stores, new object[] { i });
if (store != null)
try
{
Outlook.MAPIFolder calendar = null;
try
{
calendar = (Outlook.MAPIFolder)store.GetType().InvokeMember("GetDefaultFolder", BindingFlags.GetProperty, null, store, new object[] { Outlook.OlDefaultFolders.olFolderCalendar });
}
catch
{
continue;
}
if (calendar != null)
try
{
Outlook.Folders folders = calendar.Folders;
try
{
Outlook.MAPIFolder subfolder = null;
for (int j = 1; j < folders.Count + 1; j++)
{
subfolder = folders[j];
try
{
// add subfolder items
result.AddRange(GetAppointmentItems(subfolder));
}
finally
{ if (subfolder != null) Marshal.ReleaseComObject(subfolder); }
}
}
finally
{ if (folders != null) Marshal.ReleaseComObject(folders); }
// add root items
result.AddRange(GetAppointmentItems(calendar));
}
finally { Marshal.ReleaseComObject(calendar); }
}
finally { Marshal.ReleaseComObject(store); }
}
}
finally { Marshal.ReleaseComObject(stores); }
}
finally { Marshal.ReleaseComObject(session); }
return result;
}
List<AdxCalendarItem> GetAppointmentItems(Outlook.MAPIFolder calendarFolder)
{
List<AdxCalendarItem> result = new List<AdxCalendarItem>();
Outlook.Items calendarItems = calendarFolder.Items;
try
{
calendarItems.IncludeRecurrences = true;
Outlook.AppointmentItem appointment = null;
for (int j = 1; j < calendarItems.Count + 1; j++)
{
appointment = calendarItems[j] as Outlook.AppointmentItem;
try
{
AdxCalendarItem item = new AdxCalendarItem(
calendarFolder.Name,
appointment.Subject,
appointment.Location,
appointment.Start,
appointment.End,
appointment.Start.Date,
appointment.End.Date,
appointment.AllDayEvent,
appointment.Body);
result.Add(item);
}
finally
{
{ Marshal.ReleaseComObject(appointment); }
}
}
}
finally { Marshal.ReleaseComObject(calendarItems); }
return result;
}
}
public class AdxCalendarItem
{
public string CalendarName;
public string Subject;
public string Location;
public DateTime StartTime;
public DateTime EndTime;
public DateTime StartDate;
public DateTime EndDate;
public bool AllDayEvent;
public string Body;
public AdxCalendarItem(string CalendarName, string Subject, string Location, DateTime StartTime, DateTime EndTime,
DateTime StartDate, DateTime EndDate, bool AllDayEvent, string Body)
{
this.CalendarName = CalendarName;
this.Subject = Subject;
this.Location = Location;
this.StartTime = StartTime;
this.EndTime = EndTime;
this.StartDate = StartDate;
this.EndDate = EndDate;
this.AllDayEvent = AllDayEvent;
this.Body = Body;
}
}
Microsoft.Office.Interop.Outlook.Application oApp = null;
Microsoft.Office.Interop.Outlook.NameSpace mapiNamespace = null;
Microsoft.Office.Interop.Outlook.MAPIFolder CalendarFolder = null;
Microsoft.Office.Interop.Outlook.Items outlookCalendarItems = null;
oApp = new Microsoft.Office.Interop.Outlook.Application();
mapiNamespace = oApp.GetNamespace("MAPI"); ;
CalendarFolder = mapiNamespace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar);
outlookCalendarItems = CalendarFolder.Items;
outlookCalendarItems.IncludeRecurrences = true;
foreach (Microsoft.Office.Interop.Outlook.AppointmentItem item in outlookCalendarItems)
{
if (item.IsRecurring)
{
Microsoft.Office.Interop.Outlook.RecurrencePattern rp = item.GetRecurrencePattern();
// get all date
DateTime first = new DateTime( item.Start.Hour, item.Start.Minute, 0);
DateTime last = new DateTime();
Microsoft.Office.Interop.Outlook.AppointmentItem recur = null;
for (DateTime cur = first; cur <= last; cur = cur.AddDays(1))
{
try
{
recur = rp.GetOccurrence(cur);
MessageBox.Show(recur.Subject + " -> " + cur.ToLongDateString());
}
catch
{ }
}
}
else
{
MessageBox.Show(item.Subject + " -> " + item.Start.ToLongDateString());
}
}
}
it is working I try it but you need to add reference about
Microsoft outlook
Here's a combination of a few answers to get entries from the past 30 days. Will output to console but you can take the console log output and save to a file or whatever you want from there. Thanks to everyone for posting their code here, was very helpful!
using Microsoft.Office.Interop.Outlook;
void GetAllCalendarItems()
{
Microsoft.Office.Interop.Outlook.Application oApp = null;
Microsoft.Office.Interop.Outlook.NameSpace mapiNamespace = null;
Microsoft.Office.Interop.Outlook.MAPIFolder CalendarFolder = null;
Microsoft.Office.Interop.Outlook.Items outlookCalendarItems = null;
oApp = new Microsoft.Office.Interop.Outlook.Application();
mapiNamespace = oApp.GetNamespace("MAPI"); ;
CalendarFolder = mapiNamespace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar);
outlookCalendarItems = CalendarFolder.Items;
outlookCalendarItems.IncludeRecurrences = false;
Console.WriteLine("Showing Calendar Items From the last 30 days");
//Set your dates here...
DateTime startTime = DateTime.Now.AddDays(-31);
DateTime endTime = DateTime.Now;
string filter = "[Start] >= '"
+ startTime.ToString("g")
+ "' AND [End] <= '"
+ endTime.ToString("g") + "'";
try
{
outlookCalendarItems.Sort("[Start]", Type.Missing);
foreach (Microsoft.Office.Interop.Outlook.AppointmentItem item in outlookCalendarItems.Restrict(filter))
{
Console.WriteLine(item.Subject + " -> " + item.Start.ToLongDateString());
}
}
catch { }
Console.WriteLine("Finished");
}
GetAllCalendarItems();
calendarFolder =
mapiNamespace.GetDefaultFolder(
Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar);
Related
My problem is, I can't access and so iterate Outlook's shared calendars. I've tried several ways but they all take me back to the default calendar (i.e. my account calendar).
I tried to loop in the subfolders, the GetSharedDefaultFolder() method and using different types of objects of the Interop library but I couldn't solve it.
Here are the methods I've tried. To run the program (in particular GetMethod3() and GetMethod5()) you have to set the string "email" with your own email.
using System;
using System.Text;
using Microsoft.Office.Interop.Outlook;
namespace OutlookTest {
class Program {
static void Main(string[] args) {
OutlookSharedCalendar outlookSharedCalendar = new OutlookSharedCalendar();
}
}
public class OutlookSharedCalendar{
Microsoft.Office.Interop.Outlook.Application oApp;
NameSpace oNameSpace = null;
MAPIFolder oMAPIFolder = null;
MAPIFolder objFolder = null;
MAPIFolder objSubFolder = null;
Explorer objExplorer;
AppointmentItem objCalenderItem;
Folders objOutlookFolders;
AddressEntry addrEntry = null;
Items oCalendarItems = null;
string email = "myemail#email.com";
public OutlookSharedCalendar() {
AppStart();
GetMethod1();
AppEnd();
AppStart();
GetMethod2();
AppEnd();
AppStart();
GetMethod3();
AppEnd();
AppStart();
GetMethod4();
AppEnd();
AppStart();
GetMethod5();
AppEnd();
}
public void GetMethod1() {
oMAPIFolder = oApp.Session.GetDefaultFolder(OlDefaultFolders.olFolderCalendar);
oCalendarItems = (Items)oMAPIFolder.Items;
oCalendarItems.IncludeRecurrences = true;
foreach(AppointmentItem item in oCalendarItems) {
if(item.IsRecurring) {
RecurrencePattern oRP = item.GetRecurrencePattern();
DateTime first = new DateTime(2018, 01, 01, item.Start.Hour, item.Start.Minute, 0);
DateTime last = new DateTime(2019, 10, 31);
AppointmentItem recur = null;
for(DateTime cur = first; cur <= last; cur = cur.AddDays(1)) {
recur = oRP.GetOccurrence(cur);
Console.WriteLine(recur.Subject + " - " + cur.ToLongDateString() + " - " + recur.Body);
}
}
else {
Console.WriteLine(item.Subject + " -> " + item.Start.ToLongDateString());
}
}
}
public void GetMethod2() {
int intFolderCtr;
int intSubFolderCtr;
int intAppointmentCtr;
// >> Initialize The Base Objects
objOutlookFolders = oApp.Session.Folders;
// >> Loop Through The PST Files Added n Outlook
for(intFolderCtr = 1; intFolderCtr <= objOutlookFolders.Count; intFolderCtr++) {
objFolder = objOutlookFolders[intFolderCtr];
objExplorer = objFolder.GetExplorer();
// >> Loop Through The Folders In The PST File
for(intSubFolderCtr = 1; intSubFolderCtr <= objExplorer.CurrentFolder.Folders.Count; intSubFolderCtr++) {
objSubFolder = objExplorer.CurrentFolder.Folders[intSubFolderCtr];
// >> Check if Folder Contains Appointment Items
if(objSubFolder.DefaultItemType == OlItemType.olAppointmentItem) {
// >> Loop Through Appointment Items
for(intAppointmentCtr = 1; intAppointmentCtr <= objSubFolder.Items.Count; intAppointmentCtr++) {
// >> Get Teh Calender Item From The Calender Folder
objCalenderItem = objSubFolder.Items[intAppointmentCtr];
// >> Process Appointment Item Accordingly
Console.WriteLine(objCalenderItem.Subject + " - " + objCalenderItem.Start + " - " + objCalenderItem.Body + " - " + objCalenderItem.Location);
}
}
}
}
}
public void GetMethod3() {
DateTime dtFrom = new DateTime(DateTime.Now.Year, 01, 01);
DateTime dtTo = new DateTime(DateTime.Now.Year, 12, 31);
Recipient teamMember = oApp.Session.CreateRecipient(email);
MAPIFolder sharedCalendar = oApp.Session.GetSharedDefaultFolder(teamMember, OlDefaultFolders.olFolderCalendar);
if(sharedCalendar.DefaultMessageClass != "IPM.Appointment" || teamMember.DisplayType != 0) {
return; //Calendar not shared.
}
string restrictCriteria = "[Start]<=\"" + dtTo.ToString("g") + "\"" + " AND [End]>=\"" + dtFrom.ToString("g") + "\"";
Items results = sharedCalendar.Items.Restrict(restrictCriteria);
foreach(AppointmentItem item in results) {
Console.WriteLine(item.Subject + " - " + item.Start + " - " + item.Body + " - " + item.Location);
}
}
public void GetMethod4() {
oMAPIFolder = oApp.Session.GetDefaultFolder(OlDefaultFolders.olFolderCalendar);
DateTime dtEnd = new DateTime(DateTime.Now.Year, 12, 31);
DateTime dtStart = new DateTime(DateTime.Now.Year, 01, 01);
string restrictCriteria = "[Start]<=\"" + dtEnd.ToString("g") + "\"" +
" AND [End]>=\"" + dtStart.ToString("g") + "\"";
StringBuilder strBuilder = null;
Items folderItems = null;
Items resultItems = null;
AppointmentItem appItem = null;
int counter = default(int);
object item = null;
strBuilder = new StringBuilder();
folderItems = (Items)oMAPIFolder.Items;
folderItems.IncludeRecurrences = true;
folderItems.Sort("[Start]");
resultItems = folderItems.Restrict(restrictCriteria);
item = resultItems.GetFirst();
do {
if(item != null) {
if(item is AppointmentItem) {
counter++;
appItem = item as AppointmentItem;
Console.WriteLine(appItem.Subject + " -> " + appItem.Start.ToLongDateString());
strBuilder.AppendLine("#" + counter.ToString() +
"\tStart: " + appItem.Start.ToString() +
"\tSubject: " + appItem.Subject +
"\tLocation: " + appItem.Location);
}
item = resultItems.GetNext();
}
}
while(item != null);
}
public void GetMethod5() {
addrEntry = oApp.Session.CurrentUser.AddressEntry;
if(addrEntry.Type == "EX") {
Recipient recip = oApp.Session.CreateRecipient(email);
if(recip.Resolve()) {
Folder folder = oApp.Session.GetSharedDefaultFolder(recip, OlDefaultFolders.olFolderCalendar) as Folder;
foreach(AppointmentItem item in folder.Items) {
Console.WriteLine(item.Subject + " - " + item.Start + " - " + item.Body + " - " + item.Location);
}
}
}
}
public void AppStart() {
// >> Start Outlook
oApp = new Microsoft.Office.Interop.Outlook.Application();
}
public void AppEnd() {
// >> Close Application
oApp.Quit();
// >> Release COM Object
System.Runtime.InteropServices.Marshal.ReleaseComObject(oApp);
oApp = null;
}
}
}
I hope I can get advice on the code or if someone knows a viable alternative to Interop. Thank you all in advance.
The NameSpace.GetSharedDefaultFolder method is used to get a Folder object that represents the specified default folder for the specified user. For example, with minor changes:
public void GetMethod3() {
DateTime dtFrom = new DateTime(DateTime.Now.Year, 01, 01);
DateTime dtTo = new DateTime(DateTime.Now.Year, 12, 31);
Recipient teamMember = oApp.Session.CreateRecipient(email);
teamMember.Resolve();
if(teamMember.Resolved)
{
MAPIFolder sharedCalendar = oApp.Session.GetSharedDefaultFolder(teamMember, OlDefaultFolders.olFolderCalendar);
if(sharedCalendar.DefaultMessageClass != "IPM.Appointment" || teamMember.DisplayType != 0) {
return; //Calendar not shared.
}
string restrictCriteria = "[Start]<=\"" + dtTo.ToString("g") + "\"" + " AND [End]>=\"" + dtFrom.ToString("g") + "\"";
Items results = sharedCalendar.Items.Restrict(restrictCriteria);
foreach(AppointmentItem item in results) {
Console.WriteLine(item.Subject + " - " + item.Start + " - " + item.Body + " - " + item.Location);
}
}
}
As you may see the recipient should be resolved against your address book before trying to access a shared calendar. The Recipient.Resolve method attempts to resolve a Recipient object against the Address Book.
public void AccessOutlook()
{
Application oOutlook;
NameSpace oNs;
MAPIFolder oFldr;
try
{
oOutlook = new Application();
oNs = oOutlook.GetNamespace("MAPI");
oFldr = oNs.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
string str = "Total Mail(s) in Inbox:" + oFldr.Items.Count;
string str2 = "Total Unread items = " + oFldr.UnReadItemCount;
foreach (var oMessage in oFldr.Items)
{
MailItem mitem = null;
try
{
if (oMessage != null)
{
mitem = (MailItem)oMessage;
String savepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + #"\" + "Sridhar.html";
mitem.BodyFormat = OlBodyFormat.olFormatHTML;
mitem.SaveAs(savepath, OlSaveAsType.olHTML);
}
}
catch (System.Exception ex)
{
}
if (mitem != null)
{
string str3 = mitem.Subject;
}
}
}
catch (System.Exception ex)
{
}
finally
{
GC.Collect();
oFldr = null;
oNs = null;
oOutlook = null;
}
}
Here I want to convert mail item into PDF, hence in first step I'm trying to get mail item based on subject line and saving it in any outlook supported file formats. But I'm not able to do. Can anyone help with this?
Thanks in advance
I have seen the difference between pst and ost files and currently working on accessing the outlook pst file through the following code given below.
Is there any way to use the same code for accessing ost file? Can someone refer me to this?
private DataTable GetInboxItems()
{
DataTable inboxTable;
//try
//{
filter = "[ReceivedTime] >= '" + dtpStartDate.Value.ToString("dd/MM/yyyy 12:00 AM") + "' and [ReceivedTime] <= '" + dtpEndDate.Value.ToString("dd/MM/yyyy 11:59 PM") + "'";
Outlook.Application outlookApp = GetApplicationObject();
Outlook.Folder root = outlookApp.Session.DefaultStore.GetRootFolder() as Outlook.Folder;
EnumerateFolders(root);
//string filter = "[ReceivedTime] > '" + dtpStartDate.Value.ToString("dd/MM/yyyy") + "'";
//inbox
Outlook.MAPIFolder inboxFolder = outlookApp.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
inboxTable = CreateTable();
int count = 0;
if (inboxFolder.Items.Count > 0)
{
var restrictedItems = inboxFolder.Items.Restrict(filter);
restrictedItems.Sort("[ReceivedTime]", true); //descending
//foreach (var item in inboxFolder.Items)
foreach (var item in restrictedItems)
{
var mail = item as Outlook.MailItem;
if (mail != null)
{
//try
//{
DataRow row = inboxTable.NewRow();
//row["sn"] = (++count).ToString();
row["sn"] = mail.EntryID + " " + mail.ReceivedByEntryID;
row["MailType"] = "Inbox";
row["SenderName"] = mail.SenderName;
row["SenderEmail"] = mail.SenderEmailAddress;
row["ReceivedDate"] = mail.ReceivedTime;
row["Subject"] = mail.Subject;
row["Body"] = mail.Body != null ? (mail.Body.Length > 25 ? mail.Body.Substring(0, 25) : mail.Body) : null;
//row["Body"] = mail.Body != null ? mail.Body : "";
row["MailSize"] = mail.Size.ToString();
string attachments = null;
if (mail.Attachments.Count > 0)
{
foreach (var attachment in mail.Attachments)
{
if (((Outlook.Attachment)attachment) != null)
//attachments = ((Outlook.Attachment)attachment).FileName + " " + ((Outlook.Attachment)attachment).Size.ToString() + ", ";
attachments += (((Outlook.Attachment)attachment).Size / 1024).ToString() + " KB, ";
}
}
row["AttachmentCount"] = mail.Attachments.Count;
if (attachments != null)
row["AttachmentSize"] = attachments.Substring(0, attachments.Length - 2);
inboxTable.Rows.Add(row);
}
//catch (Exception ex)
//{
// return null;
//}
}
}
return inboxTable;
}
After I figured out how to actually build the code provided by OP, I found it very useful to get started on Outlook, so I would like to share the completed code below.
using System;
using System.Collections.Generic;//List
using System.Linq;//Array
//using System.Text;
//using System.Threading.Tasks;
using System.Diagnostics;//Process
using System.Runtime.InteropServices;//Marshal
using System.Data;//DataTable
using System.Reflection;//Missing
using Microsoft.Office.Interop.Outlook;//.OST files, needs Microsoft.Office.Interop.Outlook.dll
//TO DO: If you use the Microsoft Outlook 11.0 Object Library, uncomment the following line.
using Outlook = Microsoft.Office.Interop.Outlook;
namespace WatchOutlookMails
{
class StoreFormat
{
public DataTable GetInboxItems(DateTime dtpStartDate, DateTime dtpEndDate)
{
DataTable inboxTable;
string filter = string.Format("[ReceivedTime] >= '{0:dd/MM/yyyy 12:00 AM}' and [ReceivedTime] <= '{1:dd/MM/yyyy 11:59 PM}'", dtpStartDate, dtpEndDate);
Outlook.Application outlookApp = GetApplicationObject();
#if false//only needed if you want to select another folder
Outlook.Folder root = outlookApp.Session.DefaultStore.GetRootFolder() as Outlook.Folder;
EnumerateFolders(root);
#endif
//inbox
Outlook.MAPIFolder inboxFolder = outlookApp.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
inboxTable = CreateTable();
if (inboxFolder.Items.Count > 0)
{
Items restrictedItems = inboxFolder.Items.Restrict(filter);
const bool SortDescending = true;
restrictedItems.Sort("[ReceivedTime]", SortDescending);
foreach (var item in restrictedItems)//item is a "COM Object" (?)
{
MailItem mail = item as Outlook.MailItem;
if (mail != null)
{
//try
//{
DataRow row = inboxTable.NewRow();
//row["sn"] = (++count).ToString();
row["sn"] = mail.EntryID + " " + mail.ReceivedByEntryID;
row["MailType"] = "Inbox";
row["SenderName"] = mail.SenderName;
row["SenderEmail"] = mail.SenderEmailAddress;
row["ReceivedDate"] = mail.ReceivedTime;
row["Subject"] = mail.Subject;
row["Body"] = mail.Body != null ? (mail.Body.Length > 25 ? mail.Body.Substring(0, 25) : mail.Body) : null;
//row["Body"] = mail.Body != null ? mail.Body : "";
row["MailSize"] = mail.Size.ToString();
int AttachmentSize = 0;
foreach (Outlook.Attachment attachment in mail.Attachments)
{
if (attachment != null)
AttachmentSize += attachment.Size;
}
row["AttachmentCount"] = mail.Attachments.Count;
row["AttachmentSize"] = AttachmentSize;
inboxTable.Rows.Add(row);
//catch (Exception ex)
//{
// break;
//}
}
}
}
return inboxTable;
}
private DataTable CreateTable()
{
DataTable T = new DataTable();
T.Columns.Add("sn", typeof(string));
T.Columns.Add("MailType", typeof(string));
T.Columns.Add("SenderName", typeof(string));
T.Columns.Add("SenderEmail", typeof(string));
T.Columns.Add("ReceivedDate", typeof(string));
T.Columns.Add("Subject", typeof(string));
T.Columns.Add("Body", typeof(string));
T.Columns.Add("MailSize", typeof(int));
T.Columns.Add("AttachmentCount", typeof(int));
T.Columns.Add("AttachmentSize", typeof(int));
return T;
}
private void EnumerateFoldersInDefaultStore()
{
Outlook.Application outlookApp = GetApplicationObject();
Outlook.Folder root = outlookApp.Session.DefaultStore.GetRootFolder() as Outlook.Folder;
EnumerateFolders(root);
return;
}
private void EnumerateFolders(Outlook.Folder folder)
{
Outlook.Folders childFolders = folder.Folders;
if (childFolders.Count > 0)
{
foreach (Outlook.Folder childFolder in childFolders)
{
// Write the folder path.
//Debug.WriteLine(childFolder.FolderPath);
// Call EnumerateFolders using childFolder.
// Uses recursion to enumerate Outlook subfolders.
EnumerateFolders(childFolder);
}
}
return;
}
/// <summary>
/// obtain an Application object that represents an active instance of Microsoft Outlook,
/// if there is one running on the local computer, or to create a new instance of Outlook,
/// log on to the default profile, and return that instance of Outlook
/// </summary>
/// <returns></returns>
private Outlook.Application GetApplicationObject()
{
// source: https://msdn.microsoft.com/en-us/library/ff462097.aspx
Outlook.Application application = null;
// Check whether there is an Outlook process running.
if (Process.GetProcessesByName("OUTLOOK").Count() > 0)
{
// If so, use the GetActiveObject method to obtain the process and cast it to an Application object.
application = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
}
else
{
// If not, create a new instance of Outlook and log on to the default profile.
application = new Outlook.Application();
Outlook.NameSpace nameSpace = application.GetNamespace("MAPI");
nameSpace.Logon("", "", Missing.Value, Missing.Value);
nameSpace = null;
}
// Return the Outlook Application object.
return application;
}
}//end class
}//end ns
To fill in the missing pieces, I borrowed from https://support.microsoft.com/en-us/kb/310259, for EnumerateFolders: https://msdn.microsoft.com/en-us/library/office/ff184607.aspx
You need to educate yourself on what OST/PST is as the access to them is not much different, both are Store objects so they have the same interface.
Try this sources for a start and experiment yourself as it's the best way to understand how stuff works.
http://en.wikipedia.org/wiki/Personal_Storage_Table
http://msdn.microsoft.com/en-us/library/bb609139(v=office.14).aspx
http://msdn.microsoft.com/en-us/library/ff184648(v=office.14).aspx
http://msdn.microsoft.com/en-us/library/bb208208(v=office.12).aspx
http://www.c-sharpcorner.com/UploadFile/rambab/OutlookIntegration10282006032802AM/OutlookIntegration.aspx
I am working on an add-in for Outlook using C# and I want to be able to check the availability of calendars (mine and others'). I tried using GetSharedDefaultFolder() but it only worked with those who specifically gave me permission, even though all calendars in my company can be viewed by others (we can see the subject and times of appointments). Is there anyway I can get these information? Thanks.
EDIT: I want to emphasize that my problem is with GetSharedDefaultFolder() rather than GetDefaultFolder() (i.e. viewing others' calendars.) Also, I only need to be able to check others' calendars availability, as opposed to having full access to the calendar.
Do not access the folder directly - use Recipient.FreeBusy or AddressEntry.GetFreeBusy
Try This>>
public void GetAllCalendarItems()
{
Microsoft.Office.Interop.Outlook.Application oApp = null;
Microsoft.Office.Interop.Outlook.NameSpace mapiNamespace = null;
Microsoft.Office.Interop.Outlook.MAPIFolder CalendarFolder = null;
Microsoft.Office.Interop.Outlook.Items outlookCalendarItems = null;
oApp = new Microsoft.Office.Interop.Outlook.Application();
mapiNamespace = oApp.GetNamespace("MAPI"); ;
CalendarFolder = mapiNamespace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar); outlookCalendarItems = CalendarFolder.Items;
outlookCalendarItems.IncludeRecurrences = true;
foreach (Microsoft.Office.Interop.Outlook.AppointmentItem item in outlookCalendarItems)
{
if (item.IsRecurring)
{
Microsoft.Office.Interop.Outlook.RecurrencePattern rp = item.GetRecurrencePattern();
DateTime first = new DateTime(2008, 8, 31, item.Start.Hour, item.Start.Minute, 0);
DateTime last = new DateTime(2008, 10, 1);
Microsoft.Office.Interop.Outlook.AppointmentItem recur = null;
for (DateTime cur = first; cur <= last; cur = cur.AddDays(1))
{
try
{
recur = rp.GetOccurrence(cur);
MessageBox.Show(recur.Subject + " -> " + cur.ToLongDateString());
}
catch
{ }
}
}
else
{
MessageBox.Show(item.Subject + " -> " + item.Start.ToLongDateString());
}
}
}
Seems problem similar to this>
http://www.add-in-express.com/forum/read.php?FID=5&TID=8953
So follow discussion on this link. It might helpful to you.
I want to list(Extract) the Outlook Appointments by Date by using C#. I used restrict method to do that,
sSearch = "[Start] >= ' " + startDate + " ' and [Start] <= ' " + endDate + " '";
But, if the day after End Date(endDate) has a All Day appointment it is also listed. How to overcome from this problem ????
http://msdn.microsoft.com/en-us/library/office/gg619398(v=office.14).aspx
private void DemoAppointmentsInRange()
{
Outlook.Folder calFolder =
Application.Session.GetDefaultFolder(
Outlook.OlDefaultFolders.olFolderCalendar)
as Outlook.Folder;
DateTime start = DateTime.Now;
DateTime end = start.AddDays(5);
Outlook.Items rangeAppts = GetAppointmentsInRange(calFolder, start, end);
if (rangeAppts != null)
{
foreach (Outlook.AppointmentItem appt in rangeAppts)
{
Debug.WriteLine("Subject: " + appt.Subject
+ " Start: " + appt.Start.ToString("g"));
}
}
}
/// <summary>
/// Get recurring appointments in date range.
/// </summary>
/// <param name="folder"></param>
/// <param name="startTime"></param>
/// <param name="endTime"></param>
/// <returns>Outlook.Items</returns>
private Outlook.Items GetAppointmentsInRange(
Outlook.Folder folder, DateTime startTime, DateTime endTime)
{
string filter = "[Start] >= '"
+ startTime.ToString("g")
+ "' AND [End] <= '"
+ endTime.ToString("g") + "'";
Debug.WriteLine(filter);
try
{
Outlook.Items calItems = folder.Items;
calItems.IncludeRecurrences = true;
calItems.Sort("[Start]", Type.Missing);
Outlook.Items restrictItems = calItems.Restrict(filter);
if (restrictItems.Count > 0)
{
return restrictItems;
}
else
{
return null;
}
}
catch { return null; }
}
Similar to Tam Tam's. Just a little less code. I spent all day looking for a basic sample I could use in LinqPad. This is what I ended up with.
//using Microsoft.Office.Interop.Outlook
Application a = new Application();
Items i = a.Session.GetDefaultFolder(OlDefaultFolders.olFolderCalendar).Items;
i.IncludeRecurrences = true;
i.Sort("[Start]");
i = i.Restrict("[Start] >= '10/1/2013' AND [End] <= '10/2/2013'");
var r =
from ai in i.Cast<AppointmentItem>()
select new {ai.Start,ai.Duration,ai.Subject};
r.Dump();