I want to import contacts from Outllok via Mapi.
First step with standard contact is no problem:
MAPIFolder contactObjects =
outlookObj.Session.GetDefaultFolder(OlDefaultFolders.olFolderContacts);
foreach (ContactItem contactObject in contactObjects.Items) {
... import contact ...
}
In a second step I additionally want to import shared contacts. Only thing I found was using
OpenSharedItem(sharedContacts.vcf)
but I don't know the name of the file (shared item) I want to open.
Does someone know how to access shared contacts and can help me out?
Tobi
Update:
Thanks for the hint with the vcf-Files. But where do I find them?
Update2:
I played around with OutlookSpy. I got access to the folder with shared contacts, but only by knowing the id (which is of course different for other users):
var ns = outlookObj.GetNamespace("MAPI");
var flr = ns.GetFolderFromID("00000000176A90DED92CE6439C1CB89AFE3668F90100D1AD8F66B576B54FB731302D9BB9F6C40007E4BAC5020000");
foreach (var contactObject in flr.Items) {
...
}
How do I get access to the folder without knowing the id?
You will need to either explicitly parse the vCard files or you can use Redemption (I am its author) - it allows to import vCard files using RDOContactItem.Import - http://www.dimastr.com/redemption/RDOMail.htm#methods
Well the solution to the question as it is asked in the title is almost simple.
You just need to call:
Recipient recip = Application.Session.CreateRecipient("Firstname Lastname");
MAPIFolder sharedContactFolder = Application.Session.GetSharedDefaultFolder(recip, OlDefaultFolders.olFolderContacts);
Because this does not solve my problem I will ask another question!
I have done some programming to get contact from outlook.
I am giving you some example code to help you up with this ..It is not excatly want you want but i think this will help you with your problem...
using System.Collections.Generic;
// ...
private List<Outlook.ContactItem> GetListOfContacts(Outlook._Application OutlookApp)
{
List<Outlook.ContactItem> contItemLst = null;
Outlook.Items folderItems =null;
Outlook.MAPIFolder mapiFoldSuggestedConts = null;
Outlook.NameSpace nameSpc = null;
Outlook.MAPIFolder mapiFoldrConts = null;
object itemObj = null;
try
{
contItemLst = new List<Outlook.ContactItem>();
nameSpc = OutlookApp.GetNamespace("MAPI");
// getting items from the Contacts folder in Outlook
mapiFoldrConts =
nameSpc.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
folderItems = mapiFoldrConts.Items;
for (int i = 1; folderItems.Count >= i; i++)
{
itemObj = folderItems[i];
if (itemObj is Outlook.ContactItem)
contItemLst.Add(itemObj as Outlook.ContactItem);
else
Marshal.ReleaseComObject(itemObj);
}
Marshal.ReleaseComObject(folderItems);
folderItems = null;
// getting items from the Suggested Contacts folder in Outlook
mapiFoldSuggestedConts = nameSpc.GetDefaultFolder(
Outlook.OlDefaultFolders.olFolderSuggestedContacts);
folderItems = mapiFoldSuggestedConts.Items;
for (int i = 1; folderItems.Count >= i; i++)
{
itemObj = folderItems[i];
if (itemObj is Outlook.ContactItem)
contItemLst.Add(itemObj as Outlook.ContactItem);
else
Marshal.ReleaseComObject(itemObj);
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
finally
{
if (folderItems != null)
Marshal.ReleaseComObject(folderItems);
if (mapiFoldrConts != null)
Marshal.ReleaseComObject(mapiFoldrConts);
if (mapiFoldSuggestedConts != null)
Marshal.ReleaseComObject(mapiFoldSuggestedConts);
if (nameSpc != null) Marshal.ReleaseComObject(nameSpc);
}
return contItemLst;
}
var outlook = new Microsoft.Office.Interop.Outlook.Application();
NameSpace mapiNamespace = outlook.Application.GetNamespace("MAPI");
foreach (Store store in mapiNamespace.Stores)
{
try
{
var folder = store.GetRootFolder();
foreach(MAPIFolder subfolder in folder.Folders)
{
if ( subfolder.Name == "Inbox")
{
foreach(dynamic message in subfolder.Items.Restrict("[MessageClass]='IPM.Sharing'"))
{
if (message.Class == 104)//SharingItem
{
Folder sharedFolder = message.OpenSharedFolder();
if (sharedFolder.DefaultMessageClass == "IPM.Contact")
{
//this is your folder
}
}
}
}
}
}
catch (System.Exception ex)
{
continue;
}
}
Related
I have in my Outlook 2010-Add-In (c#) many folders. They are in my private post box or in one of my shared post boxes.
Now I am looking for a solution to find out, how to get the right email address (sender / recipient) associated with a dedicated folder. It could be any folder from my private or anyone of my shared post boxes.
I think, maybe I could use the EntryId / StoreId from the folder item to identify the corresponding email address.
I know already, that I could get the email address from any mail item but I'm not looking for this solution.
I like to answer my own questions: I think that I've found a plausible solution.
I do not treat any exceptions inside the function, I do that from outside.
private string GetSMTPAddressByFolderItem(Outlook.MAPIFolder mapiFolder)
{
string PR_MAILBOX_OWNER_ENTRYID = #"http://schemas.microsoft.com/mapi/proptag/0x661B0102";
string PR_SMTP_ADDRESS = #"http://schemas.microsoft.com/mapi/proptag/0x39FE001E";
Outlook.Store store = null;
Outlook.NameSpace ns = null;
Outlook.AddressEntry sender = null;
Outlook._ExchangeUser exchUser = null;
try
{
if (mapiFolder == null)
{
return null;
}
// Get the parent store.
store = mapiFolder.Store;
string storeOwnerEntryId = store.PropertyAccessor.BinaryToString(store.PropertyAccessor.GetProperty(PR_MAILBOX_OWNER_ENTRYID)) as string;
ns = Application.GetNamespace(Constants.OL_NAMESPACE); // i.e. "MAPI"
sender = ns.GetAddressEntryFromID(storeOwnerEntryId);
if (sender != null)
{
if (sender.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeUserAddressEntry ||
sender.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeRemoteUserAddressEntry)
{
exchUser = sender.GetExchangeUser();
if (exchUser != null)
{
return exchUser.PrimarySmtpAddress;
}
else
{
return null;
}
}
else
{
return sender.PropertyAccessor.GetProperty(PR_SMTP_ADDRESS) as string;
}
}
return null;
}
finally
{
if (ns != null)
{
Marshal.ReleaseComObject(ns);
ns = null;
}
if (store != null)
{
Marshal.ReleaseComObject(store);
store = null;
}
if (sender != null)
{
Marshal.ReleaseComObject(sender);
sender = null;
}
if (exchUser != null)
{
Marshal.ReleaseComObject(exchUser);
exchUser = null;
}
}
}
I am using below code to retrieve the different mail parameter from MS outlook 2010. but I am not able to get CC email address. CC property of MailItem class is returning Name, not email address.
NameSpace _nameSpace;
ApplicationClass _app;
_app = new ApplicationClass();
_nameSpace = _app.GetNamespace("MAPI");
object o = _nameSpace.GetItemFromID(EntryIDCollection);
MailItem Item = (MailItem)o;
string HTMLbpdyTest = Item.HTMLBody;
CreationTime = Convert.ToString(Item.CreationTime);
strEmailSenderEmailIdMAPI = Convert.ToString(Item.SenderEmailAddress);
strEmailSenderName = Item.SenderName;
Subject = Item.Subject;
string CCEmailAddress = Item.CC;
Please suggest, how can I get CC email addresses?
Loop through the MailItem.Recipients collection and for each Recipient object check its Type property; olCC is what you want. You can then read the Recipient.Address property.
EDIT: Off the top of my head.
foreach (Recipient recip in Item.Recipients)
{
if (recip.Type == OlMailRecipientType.olCC)
{
if (CCEmailAddress.length > 0) CCEmailAddress += ";";
CCEmailAddress += recip.Address;
}
}
I was inspired by #Dmitry's answer and tried a few things on my own to have these lines of code fix my problems and give me an array of the cc-ed addresses that are present in a given mail item.
public string[] GetCCAddress(MailItem mailItem)
{
string email;
Outlook.ExchangeUser exUser;
List <string> ccEmailAddressList = new List<string>();
foreach (Recipient recip in mailItem.Recipients)
{
if ((OlMailRecipientType)recip.Type == OlMailRecipientType.olCC)
{
email=recip.Address;
if (!email.Contains("#"))
{
exUser = recip.AddressEntry.GetExchangeUser();
email = exUser.PrimarySmtpAddress;
}
ccEmailAddressList.Add(email);
}
}
This statement if (!email.Contains("#")) is to avoid calling exUser.PrimarySmtpAddress on an actual email address and restrict that to entries such as " /O=EXG5/OU=EXCHANGE ADMINISTRATIVE GROUP (FYDIBOHF23SPDLT)/CN=RECIPIENTS/CN=Test88067"
public static int ConnectToOutlook()
{
try
{
Outlook.Application oApp = new Outlook.Application();
Outlook.NameSpace oNS = oApp.GetNamespace("mapi");
oNS.Logon(Missing.Value, Missing.Value, false, true);
Outlook.MAPIFolder oInbox = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox).Parent;
List<string> ccRecipient = new List<string>();
foreach (MAPIFolder folder in oInbox.Folders)
{
if (folder.FullFolderPath.Contains("Inbox"))
{
foreach (MAPIFolder subFolder in folder.Folders)
{
try
{
if (subFolder.FullFolderPath.Contains("Folder Name Inside Inbox"))
{
foreach (object folderItems in subFolder.Items)
{
if (folderItems is Outlook.MailItem)
{
Outlook.MailItem email_Msg = (Outlook.MailItem)folderItems;
Console.WriteLine("Subject=>" + email_Msg.Subject);
//Console.WriteLine("From=>" + email_Msg.SenderEmailAddress);
//Console.WriteLine("Cc=>" + email_Msg.CC);
//Console.WriteLine("Recipients=>" + email_Msg.Recipients[1].Address);
foreach (Recipient recipient in email_Msg.Recipients)
{
if ((OlMailRecipientType)recipient.Type == OlMailRecipientType.olCC)
{
Console.WriteLine("Cc=>" + recipient.AddressEntry.GetExchangeUser().PrimarySmtpAddress);
}
}
}
}
}
}
catch (System.Exception error)
{
Console.WriteLine();
Console.WriteLine(error.Message);
}
}
}
}
}
catch (System.Exception e)
{
Console.WriteLine("{0} Exception caught: ", e);
}
return 0;
}
Try
Item.CC.Address
or
((MailAddress)Item.CC).Address
I've been having a little weekend project for myselff which involves getting all my ToDo tasks from Outlook, put them in a DataGridView and me being able to edit and export them.
The only problem I've been running into is me being unable to get the task specific properties for flagged emails while they still exist, I just don't see any way to access them.
Here is a portion of my current code.
private void retrieveTasks()
{
//Clear datagrid so we won't have duplicate information
taskList.Rows.Clear();
//Define some properties so we can use these to retrieve the tasks
Outlook.Application app = null;
_NameSpace ns = null;
Store outlookStore = null;
Outlook.MAPIFolder taskFolder = null;
Outlook.MAPIFolder specialFolder = null;
TaskItem task = null;
DateTime nonDate = new DateTime(4501, 1, 1);
try
{
//Connect to Outlook via MAPI
app = new Outlook.Application();
ns = app.GetNamespace("MAPI");
ns.Logon(null, null, false, false);
/*
outlookStore = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox).Store;
taskFolder = outlookStore.GetSpecialFolder(Microsoft.Office.Interop.Outlook.OlSpecialFolders.olSpecialFolderAllTasks);
*/
//Get the taskfolder containing the Outlook tasks
//taskFolder = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderTasks);
outlookStore = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox).Store;
taskFolder = outlookStore.GetSpecialFolder(OlSpecialFolders.olSpecialFolderAllTasks);
//Console.WriteLine(specialFolder.Items[1].Subject.ToString());
/*for (int i = 1; i <= specialFolder.Items.Count; i++)
{
//task = (Outlook.TaskItem)specialFolder.Items[i];
Console.WriteLine(specialFolder.Items[i].ToString());
}*/
for (int i = 1; i <= taskFolder.Items.Count; i++)
{
//Get task from taskfolder
Object item = taskFolder.Items[i];
if (item is Outlook.MailItem)
{
MailItem mail = (Outlook.MailItem)item;
if (mail.TaskCompletedDate.Equals(nonDate))
{
string percentComplete = "";
string taskPrio = "";
if (mail.UserProperties.Find("Prio") == null)
{
taskPrio = "";
}
else
{
taskPrio = mail.UserProperties.Find("Prio").Value.ToString();
}
//mail.UserProperties.
if (mail.UserProperties.Find("% Complete") == null)
{
percentComplete = "";
}
else
{
percentComplete = mail.UserProperties.Find("% Complete").Value.ToString();
}
//Add the tasks details to the datagrid
taskList.Rows.Add(
i.ToString(),
checkForNull(mail.Subject),
parseDate(mail.TaskStartDate.ToString()),
parseDate(mail.TaskDueDate.ToString()),
percentComplete, "Taak voltooid",
//statusToFriendlyName(mail.Status.ToString()),
taskPrio
);
}
}
else if (item is Outlook.TaskItem)
{
task = (Outlook.TaskItem)item;
Console.WriteLine(task.Subject);
if (task.Complete == false)
{
string taskPrio = "";
//Make sure custom task property is failed or set it to empty text to prevent crashes
if (task.UserProperties.Find("Prio") == null)
{
taskPrio = "";
}
else
{
taskPrio = task.UserProperties.Find("Prio").Value.ToString();
}
//Add the tasks details to the datagrid
taskList.Rows.Add(
i.ToString(),
task.Subject.ToString(),
parseDate(task.StartDate.ToString()),
parseDate(task.DueDate.ToString()),
task.PercentComplete.ToString(),
statusToFriendlyName(task.Status.ToString()),
taskPrio
);
}
}
}
}
catch (System.Runtime.InteropServices.COMException ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
//Release Outlook sources
ns = null;
app = null;
}
}
So specifically I am looking for the "% complete" property and the status property, everything else I am able to work around on.
It would make my life SO MUCH EASIER if I can get this to work :)
Hope to hear from anyone on here!
Jeffrey
Do you mean you need to retrieve the task specific properties from a MailItem object (as opposed to the TaskItem object)?
Take a look at the message with OutlookSpy (I am its author) - click IMessage button, look at the MAPI properties in the GetProps tab. Any property can be accessed using MailItem.PropertyAccessor.GetProperty. The DASL name to be used by GetProperty is displayed by OutlookSpy (select the property in the IMessage window, see the DASL edit box).
I am developing a WPF-C# application and fetching MS Outlook 2010 contact items using Redemption. It is working fine if my Outlook has only one SMTP account. But if I configure another account which is exchange server account then I don't get any contact item from the same code. Following is my code:
Interop.Redemption.RDOItems folderItems = null;
Interop.Redemption.RDOFolder folderContacts = null;
Interop.Redemption.RDOFolder folderSuggestedContacts = null;
List<GMContactItem> allOutlookContacts = null;
object itemObj = null;
List<Interop.Redemption.RDOContactItem> contactItemsList = null;
try
{
folderContacts = (RDOFolder)RDOSessionItem.GetDefaultFolder(Interop.Redemption.rdoDefaultFolders.olFolderContacts);
contactItemsList = new List<RDOContactItem>();
folderItems = folderContacts.Items;
for (int i = 1; folderItems.Count >= i; i++)
{
itemObj = folderItems[i];
if (itemObj is Interop.Redemption.RDOContactItem)
contactItemsList.Add(itemObj as RDOContactItem);
else
Marshal.ReleaseComObject(itemObj);
}
Marshal.ReleaseComObject(folderItems);
folderItems = null;
// getting items from the Suggested Contacts folder in Outlook
folderSuggestedContacts = RDOSessionItem.GetDefaultFolder(
rdoDefaultFolders.olFolderSuggestedContacts);
if (folderSuggestedContacts != null)
{
folderItems = folderSuggestedContacts.Items;
for (int i = 1; folderItems.Count >= i; i++)
{
itemObj = folderItems[i];
if (itemObj is Interop.Redemption.RDOContactItem)
contactItemsList.Add(itemObj as Interop.Redemption.RDOContactItem);
else
Marshal.ReleaseComObject(itemObj);
}
}
}
catch (System.Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.ToString());
}
When I delete my exchange server account then it work fine and if I add exchange server account in Outlook then this code has no exception but don't give any contact item. Can anybody suggest me that what could be the issue here. Thanks in advance.
-Surya
Are you looking at the GAL entries? These address entries exist in GAL (AD based), not in the Contacts folder of the Exchange mailbox.
If you need to open the Contacts folder of the (non-default) PST store, call RDOStore.GetDefaultFolder(olFolderContacts) instead of RDOSession.GetDefaultFolder (which returns a folder from the default store).
The secondary PST store can be opened using the RDOSession.Stores collection.
I have the following code to enumerate all the email address of my contacts but I am not able to do so with the exception point at this line
Outlook.ContactItem oAppt = (Outlook.ContactItem)oItems;
Could someone help me out so that I can enumerate all the email address of my contacts in Microsoft outlook ?
namespace RetrieveContacts
{
public class Class1
{
public static int Main(string[] args)
{
try
{
Outlook.Application oApp = new Outlook.Application();
Outlook.NameSpace oNS = oApp.GetNamespace("mapi");
Outlook.MAPIFolder oContacts = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
Outlook.Items oItems = oContacts.Items;
Outlook.ContactItem oAppt = (Outlook.ContactItem)oItems;
for (int i = 0; i <= oItems.Count; i++)
{
System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\EmailAddress.txt");
file.WriteLine(oAppt.Email1Address);
file.Close();
}
oNS.Logoff();
oAppt = null;
oItems = null;
oContacts = null;
oNS = null;
oApp = null;
}
catch (Exception e)
{
System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\Exception.txt");
file.WriteLine(e);
file.Close();
}
return 0;
}
}
}
Without knowing Outlook's object model by heart I'd guess that Outlook.Items is a collection of ContactItems and thus cannot directly be cast to a single ContactItem. Other concerns:
You're creating and writing to your file within the loop, so it would get overwritten each time
You need to validate that the item is a ContactItem or your cast will throw an error.
the file access should be in a using block so it gets closed automatically if an Exception is thrown
Your for loop is going from 0 to Count when it should be going from 0 to Count-1 if the collection is 0-based
Try changing your loop to something like this:
Outlook.Items oItems = oContacts.Items;
using(System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\EmailAddress.txt"))
{
for (int i = 0; i < oItems.Count; i++) // Note < instead of <=
{
// Will be null if oItems[i] is not a ContactItem
Outlook.ContactItem oAppt = oItems[i] as Outlook.ContactItem;
if(oAppt != null)
file.WriteLine(oAppt.Email1Address);
}
}
file.Close();
oNS.Logoff();