Microsoft.Office.Interop.Outlook.Application Application = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MAPIFolder inBox = Application.ActiveExplorer().Session.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
Microsoft.Office.Interop.Outlook.Items inBoxItems = inBox.Items;
Microsoft.Office.Interop.Outlook.MailItem newEmail = null;
foreach (object collectionItem in inBoxItems)
{
newEmail = collectionItem as Microsoft.Office.Interop.Outlook.MailItem;
if (newEmail != null)
{
if (newEmail.Attachments.Count > 0)
{
for (int i = 1; i <= newEmail
.Attachments.Count; i++)
{
newEmail.Attachments[i].SaveAsFile
(#"C:\TestFileSave\" +
newEmail.Attachments[i].FileName);
}
}
}
}
I have copy mail from outlook and paste into flex-grid in window application but getting zero attachment count but in mail there are attachments like excel , doc , etc. files.
int extractFileParentId = pkUniqueId;
List<ZipExtracFile> extractFileList = lts;
MsgReader.Outlook.Storage.Message message = new MsgReader.Outlook.Storage.Message(fileNames);
foreach (var attachment in message.Attachments)
{
string fileName = string.Empty;
pkUniqueId = pkUniqueId + 1;
if (attachment.GetType() == typeof(MsgReader.Outlook.Storage.Attachment))
{
var attach = (MsgReader.Outlook.Storage.Attachment)attachment;
fileName = Path.Combine(tempPath, (attach).FileName);
File.WriteAllBytes(fileName, attach.Data);
extractFileList.Add(new ZipExtracFile { pkUniqueId = pkUniqueId, fileName = fileName, parentId = extractFileParentId });
if(Path.GetExtension(fileName).ToLower() == ".msg")
{
ExtractMsgFile(fileName, ref pkUniqueId, ref tempPath, lts);
}
}
}
message.Dispose();
This is used to fetch documents from ".msg" file documents , with multilevel ".msg" file and it can download at specific location. For this need to add only MsgReader.dll
How do i access an outlook account inbox using c#? I've tried using the outlook object model and imap but it only displays the outlook account logged into my machine. I try logging into a different account with its username and password but it still logs into my local machine account. I read that logging out and closing outlook should fix this problem but it didn't change the results
Here is the code
using System;
using System.Reflection;
using Outlook = Microsoft.Office.Interop.Outlook;
namespace ConsoleApplication1
{
public class Class1
{
public static int Main(string[] args)
{
try
{
Outlook.Application oApp = new Outlook.Application();
// Get the MAPI namespace.
Outlook.NameSpace oNS = oApp.GetNamespace("MAPI");
oNS.Logon("email address placeholder", "password placeholder", false, true);
//Get the Inbox folder.
Outlook.MAPIFolder oInbox = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
String user = oNS.CurrentUser.EntryID;
//Get the Items collection in the Inbox folder.
Outlook.Items oItems = oInbox.Items;
Console.WriteLine(oItems.Count);
Outlook.MailItem oMsg = (Outlook.MailItem)oItems.GetFirst();
Console.WriteLine(oMsg.Subject);
Console.WriteLine(oMsg.SenderName);
Console.WriteLine(oMsg.ReceivedTime);
Console.WriteLine(oMsg.Body);
int AttachCnt = oMsg.Attachments.Count;
Console.WriteLine("Attachments: " + AttachCnt.ToString());
if (AttachCnt > 0)
{
for (int i = 1; i <= AttachCnt; i++)
Console.WriteLine(i.ToString() + "-" + oMsg.Attachments[i].DisplayName);
}
for (int i = 0; i < oItems.Count; i++)
{
if (oItems.GetNext() is Outlook.MailItem)
{
oMsg = (Outlook.MailItem)oItems.GetNext();
Console.WriteLine(oMsg.Subject);
Console.WriteLine(oMsg.SenderName);
Console.WriteLine(oMsg.ReceivedTime);
Console.WriteLine(oMsg.Body);
AttachCnt = oMsg.Attachments.Count;
if (AttachCnt > 0)
{
for (int j = 1; j <= AttachCnt; j++)
Console.WriteLine(j.ToString() + "-" + oMsg.Attachments[j].DisplayName);
}
Console.WriteLine("Attachments: " + AttachCnt.ToString());
Console.WriteLine("CURRENT EMAIL # IS: " + i);
}
else
{
oItems.GetNext();
Console.WriteLine("NOT AN EMAIL");
Console.WriteLine("CURRENT EMAIL # IS: " + i);
}
}
oNS.Logoff();
oMsg = null;
oItems = null;
oInbox = null;
oNS = null;
oApp = null;
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught: ", e);
}
return 0;
}
}
}
You can try using this code:
public List<Outlook.MailItem> GetMails()
{
Microsoft,Office.Interop.Outlook.NameSpace nameSpace = OutLookName.Application.GetNameSpace("MAPI");
nameSpace.Logon("","",System.Reflection.Missing.Value,System.Reflection.Missing.Value);
Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = nameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
List<Outlook.MailItem> eMails = new List<Outlook.MailItem>();
foreach(Microsoft.Office.Interop.Outlook.MailItem mailItem in inboxFolder.Items)
{
if(mailItem.UnRead)
eMails.Add(mailItem);
}
return eMails;
}
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’m working on an ASP webpage that uses a Minitab DCOM object. My problem is that this DCOM object stops responding (hangs) if the Identity is set as “This User” under Component Services (DCONCNFG) but if I log into windows with the user that I used under “This User” and set the Identity as “Interactive user” everything works fine.
My question is what is different between DCOM Identity “The interactive user” and “This user” if the username is the same (Administrator)?
Mainly this webpage uses Minitab to generate graphs. Before it hangs it does generate graphs but only 5 or 6 graphs then it stops responding.
Here is the C# code incase you are wondering where it hangs:
using System;
using System.Web;
using System.Web.UI.WebControls;
using Mtb; // Minitab Library (Mtb 16.0 Type Library)
using System.IO;
using System.Data;
using System.Runtime.InteropServices;
using System.Threading;
namespace TRWebApp.TestDetails
{
public partial class TestDetails : System.Web.UI.Page
{
// MiniTab Stuff
Mtb.IApplication g_MtbApp;
Mtb.IProject g_MtbProj;
Mtb.IUserInterface g_MtbUI;
Mtb.IWorksheets g_MtbWkShts;
Mtb.ICommands g_MtbCommands;
Mtb.IOutputs g_MtbOutputs;
Mtb.IGraph g_MtbGraph;
Mtb.IOutputs g_MtbOutputs2;
Mtb.IGraph g_MtbGraph2;
int g_GraphIdx = 1;
int g_Loop = 1;
// Tests Table
enum testsTable { TestIdx, TestSeq, ParamName, LSL, USL, Units };
Tools tools = new Tools();
string g_SessionID = "";
Mtb_DataSetTableAdapters.XBarTableAdapter xbarTA = new Mtb_DataSetTableAdapters.XBarTableAdapter();
protected void Page_Init(object sender, EventArgs e)
{
g_MtbApp = new Application();
g_MtbProj = g_MtbApp.ActiveProject;
g_MtbUI = g_MtbApp.UserInterface;
g_MtbWkShts = g_MtbProj.Worksheets;
g_MtbCommands = g_MtbProj.Commands;
g_MtbUI.DisplayAlerts = false;
g_MtbUI.Interactive = false;
g_MtbUI.UserControl = false;
lblProductDesc.Text = ""; // Start with a clear variable
g_SessionID = HttpContext.Current.Session.SessionID;
string imgFolder = "Images/Mtb/";
string mtbSessionPath = Server.MapPath(ResolveUrl("~/" + imgFolder)) + g_SessionID;
Directory.CreateDirectory(mtbSessionPath);
Array.ForEach(Directory.GetFiles(mtbSessionPath), File.Delete); // Delete all the files from the directory
Session["MtbSessionPath"] = mtbSessionPath; // Store the Session Path so we can later delete it
// Add the two image columns to the grid view
GridView1.AutoGenerateColumns = false;
ImageField imgColumn = new ImageField();
imgColumn.HeaderText = "Scatterplot";
imgColumn.DataImageUrlField = "TestIdx";
imgColumn.DataImageUrlFormatString = "~\\Images\\Mtb\\" + g_SessionID + "\\{0}.GIF";
imgColumn.ControlStyle.CssClass = "MtbImgDetail";
GridView1.Columns.Add(imgColumn);
ImageField img2Column = new ImageField();
img2Column.HeaderText = "Histogram";
img2Column.DataImageUrlField = "TestIdx";
img2Column.DataImageUrlFormatString = "~\\Images\\Mtb\\" + g_SessionID + "\\H{0}.GIF";
img2Column.ControlStyle.CssClass = "MtbImgDetail";
GridView1.Columns.Add(img2Column);
}
protected void Page_Load(object sender, EventArgs e)
{
try
{
lblErrMsg.Text = "";
// Fill dates if they are empty
if (String.IsNullOrEmpty(tbxFromDate.Text))
tbxFromDate.Text = String.Format("{0:MM/01/yy}", DateTime.Today, null, DateTime.Today);
if (String.IsNullOrEmpty(tbxToDate.Text))
tbxToDate.Text = String.Format("{0:MM/dd/yy}", DateTime.Today);
}
catch (Exception ex)
{
lblErrMsg.Text = ex.Message;
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex >= 0)
{
// Get the data for the parameter name
DataTable dt = xbarTA.GetXBarData(lbxProduct.SelectedValue, Convert.ToDateTime(tbxFromDate.Text), Convert.ToDateTime(tbxToDate.Text), e.Row.Cells[(int)testsTable.ParamName].Text);
// Pass the data to an object array so we can pass it to minitab
object[] data = new object[dt.Rows.Count];
object[] time = new object[dt.Rows.Count];
int i = 0;
foreach (DataRow dr in dt.Rows)
{
if (tools.IsNumeric(dr["ParamValue"]))
{
data[i] = Convert.ToDouble(dr["ParamValue"]);
time[i] = i;
}
i++;
}
if (dt.Rows.Count > 1) // Do graphs with at least two measurements
{
// Only pass it to minitab if we have numeric data
if (!ReferenceEquals(data[0], null)) // if it is not null it means it has a numeric value
{
g_MtbWkShts.Item(1).Columns.Add().SetData(data);
g_MtbWkShts.Item(1).Columns.Add().SetData(time);
g_MtbWkShts.Item(1).Columns.Item(1).Name = e.Row.Cells[(int)testsTable.ParamName].Text + " (" + e.Row.Cells[(int)testsTable.Units].Text + ")";
g_MtbWkShts.Item(1).Columns.Item(2).Name = "Time";
//// H E R E
////
//// FOLLOWING LINE HANGS AFTER GENERATING 6 GRAPHS WHEN THE IDENTITY "THIS USER" IS SET
////
g_MtbProj.ExecuteCommand("Plot C1*C2;\nSymbol;\nConnect.", g_MtbWkShts.Item(1));
// Convert LSL and USL to Decimal
if (tools.IsNumeric(e.Row.Cells[(int)testsTable.LSL].Text.Trim()) && tools.IsNumeric(e.Row.Cells[(int)testsTable.USL].Text.Trim()))
{
if (Convert.ToDouble(e.Row.Cells[(int)testsTable.LSL].Text) < Convert.ToDouble(e.Row.Cells[(int)testsTable.USL].Text))
{
g_MtbProj.ExecuteCommand("Capa C1 " + dt.Rows.Count.ToString() + ";\nLspec " + e.Row.Cells[(int)testsTable.LSL].Text + ";\nUspec " + e.Row.Cells[(int)testsTable.USL].Text + ";\nPooled;\nAMR;\nUnBiased;\nOBiased;\nToler 6;\nWithin;\nOverall;\nCStat.", g_MtbWkShts.Item(1));
}
else
{
g_MtbProj.ExecuteCommand("Histogram C1;\nBar;\nDistribution;\nNormal.", g_MtbWkShts.Item(1));
}
}
else
{
g_MtbProj.ExecuteCommand("Histogram C1;\nBar;\nDistribution;\nNormal.", g_MtbWkShts.Item(1));
}
try
{
g_MtbOutputs = g_MtbCommands.Item(g_GraphIdx).Outputs;
g_GraphIdx++;
g_MtbOutputs2 = g_MtbCommands.Item(g_GraphIdx).Outputs;
g_GraphIdx++;
string graphPath = "";
if (g_MtbOutputs.Count > 0)
{
g_MtbGraph = g_MtbOutputs.Item(1).Graph;
graphPath = Server.MapPath(ResolveUrl("~/Images/Mtb/")) + g_SessionID + Path.DirectorySeparatorChar + e.Row.Cells[(int)testsTable.TestIdx].Text + ".gif";
g_MtbGraph.SaveAs(graphPath, true, MtbGraphFileTypes.GFGIF, 600, 400, 96);
}
if (g_MtbOutputs2.Count > 0)
{
g_MtbGraph2 = g_MtbOutputs2.Item(1).Graph;
graphPath = Server.MapPath(ResolveUrl("~/Images/Mtb/")) + g_SessionID + Path.DirectorySeparatorChar + "H" + e.Row.Cells[(int)testsTable.TestIdx].Text + ".gif";
g_MtbGraph2.SaveAs(graphPath, true, MtbGraphFileTypes.GFGIF, 600, 400, 96);
}
}
catch (Exception ex)
{
lblErrMsg.Text = "Test Idx: " + e.Row.Cells[(int)testsTable.TestIdx].Text + " seems to have problems.<BR />Error: " + ex.Message;
}
g_MtbWkShts.Item(1).Columns.Delete(); // Delete all the columns (This line of code is needed otherwise the Mtb.exe will still running on the server side task manager
}
else
{
// Copy the No numeric image as a graph
File.Copy(Server.MapPath("~\\Images\\Mtb\\NaN.gif"), Server.MapPath("~\\Images\\Mtb\\" + g_SessionID + "\\" + e.Row.Cells[(int)testsTable.TestIdx].Text + ".gif"));
File.Copy(Server.MapPath("~\\Images\\Mtb\\NaN.gif"), Server.MapPath("~\\Images\\Mtb\\" + g_SessionID + "\\H" + e.Row.Cells[(int)testsTable.TestIdx].Text + ".gif"));
}
}
}
}
protected void GridView1_Unload(object sender, EventArgs e)
{
// All these lines of code are needed otherwise the Mtb.exe will not be close on the task manager (server side)
GC.Collect();
GC.WaitForPendingFinalizers();
if (g_MtbGraph != null)
Marshal.ReleaseComObject(g_MtbGraph); g_MtbGraph = null;
if (g_MtbOutputs != null)
Marshal.ReleaseComObject(g_MtbOutputs); g_MtbOutputs = null;
if (g_MtbGraph2 != null)
Marshal.ReleaseComObject(g_MtbGraph2); g_MtbGraph2 = null;
if (g_MtbOutputs2 != null)
Marshal.ReleaseComObject(g_MtbOutputs2); g_MtbOutputs2 = null;
if (g_MtbCommands != null)
Marshal.ReleaseComObject(g_MtbCommands); g_MtbCommands = null;
if (g_MtbWkShts != null)
Marshal.ReleaseComObject(g_MtbWkShts); g_MtbWkShts = null;
if (g_MtbUI != null)
Marshal.ReleaseComObject(g_MtbUI); g_MtbUI = null;
if (g_MtbProj != null)
Marshal.ReleaseComObject(g_MtbProj); g_MtbProj = null;
if (g_MtbApp != null)
{
g_MtbApp.Quit();
Marshal.ReleaseComObject(g_MtbApp); g_MtbApp = null;
}
}
}
}
I'm using:
Windows Server 2008 R2 Standard (SP 1)
IIS 7.5.7600.16385
Framework 4.0.30319
Visual Studio 2010 Version 10.0.30319.1
Minitab 16.1.0
Thank you,
Pablo
Just a guess, based on something that happened to me ages ago:
For some reason, Minitab is displaying a modal error dialog of some kind. When you configure DCOM to launch as some user (not the interactive user), the process gets its own "windows station" which is not actually visible to you as the logged in user. So there is a dialog popped up somewhere invisible, waiting for input forever, hence the hang. Why the dialog is displaying is a different matter, likely a permissions issue. Sometimes, certain parts of the registry are available or not available in different activation contexts, for example.
Thanks Jlew for the link. It helped me to solve the problem by changing a register value from “Shared Section=1024,20480,768” to “Shared Section=1024,20480,2304” (3 times bigger) on this register key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\SubSystems\Windows
This value specifies a memory heap size when the user is not logged on. I guess it was not enough to handle all the MiniTab graphs.
Pablo
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);