I have an application that uses the COM interface to communicate with Outlook.
I have a dropdown box, which has all the calendars from all the accounts.
There are some reported cases, where using exchange and Outlook 2010, the application hangs when loading the list of calendars. Could it be, that it has something to do with the code (shown below) or an anti-virus blocking the access for the address information?
It randomly fails for some Exchange accounts.
private void AppLoad(object sender, EventArgs e)
{
Outlook.Application msOutlook = new Outlook.Application();
Outlook.NameSpace session = msOutlook.Session;
Outlook.Stores stores = session.Stores;
foreach (Outlook.MAPIFolder folder in session.Folders)
{
GetFolders(folder, msOutlook);
}
if(calendarSelector.Items.Count==0)
{
StoreAndCalendar ci = new StoreAndCalendar();
ci.Text = "Default";
ci.Account = "Noaccount";
ci.Storename = "Noaccount";
ci.Value = "Noaccount";
calendarSelector.Items.Add(ci);
}
else
{
try
{
calendarSelector.SelectedIndex = 0;
}
catch { }
}
//preselect default calendar and account
GetDefaultCalendarAndAccount();
}
public void GetFolders(Outlook.MAPIFolder folder, Outlook.Application app)
{
if (folder.Folders.Count == 0)
{
if (folder.DefaultItemType == Outlook.OlItemType.olAppointmentItem)
{
StoreAndCalendar ci = new StoreAndCalendar();
Outlook.Account acc = GetAccountForFolder(folder, app);
if (acc != null)
{
if (!folder.FullFolderPath.Contains("Deleted"))
{
ci.Text = folder.Name + " - " + acc.DisplayName;
ci.Account = acc.DisplayName;
ci.Storename = acc.UserName;
ci.Value = folder.Name;
calendarSelector.Items.Add(ci);
}
}
}
}
else
{
if (folder.DefaultItemType == Outlook.OlItemType.olAppointmentItem)
{
StoreAndCalendar ci = new StoreAndCalendar();
Outlook.Account acc = GetAccountForFolder(folder, app);
if (acc != null)
{
if (!folder.FullFolderPath.Contains("Deleted"))
{
ci.Text = folder.Name + " - " + acc.DisplayName;
ci.Account = acc.DisplayName;
ci.Storename = acc.UserName;
ci.Value = folder.Name;
calendarSelector.Items.Add(ci);
}
}
}
foreach (Outlook.MAPIFolder subFolder in folder.Folders)
{
GetFolders(subFolder, app);
}
}
}
Outlook.Account GetAccountForFolder(Outlook.MAPIFolder folder, Outlook.Application app)
{
// Obtain the store on which the folder resides.
Outlook.Store store = folder.Store;
// Enumerate the accounts defined for the session.
foreach (Outlook.Account account in app.Session.Accounts)
{
// Match the DefaultStore.StoreID of the account
// with the Store.StoreID for the currect folder.
if (account.DeliveryStore.StoreID == store.StoreID)
{
// Return the account whose default delivery store
// matches the store of the given folder.
return account;
}
}
// No account matches, so return null.
return null;
}
public void GetDefaultCalendarAndAccount()
{
try
{
Outlook.Application OutlookApp = new Outlook.Application();
Outlook.NameSpace ns;
Outlook.MAPIFolder defaultfolder;
Outlook.Account defaultaccount;
ns = OutlookApp.Session;
ns.SendAndReceive(false);
defaultfolder = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar);
defaultaccount = GetAccountForFolder(defaultfolder, OutlookApp);
String defaultaccandfold = defaultfolder.Name + " - " + defaultaccount.DisplayName;
int index = 0;
for (int i = 0; i < calendarSelector.Items.Count; i++)
{
string value = calendarSelector.GetItemText(calendarSelector.Items[i]);
if (value == defaultaccandfold)
{
calendarSelector.SelectedIndex = index;
}
index++;
}
}
catch { }
}
What is the best way of going through the accounts, and all of their subfolders, listing all the valid calendars?
Also, selecting the default calendar: is that the way it has to be done?
Thank you!
You're on target as to the best approach. But some suggestions:
There's no need to iterate through Accounts, just parse Stores
Don't process Stores for non-email Store objects, like SharePoint Lists and Internet Calendars (unless you want those kinds of Calendars)
Don't use foreach loops with the Outlook Object Model, use for loops so you can explicitly call Marshal.ReleaseComObject on every variable that references an Outlook object
Your call to NameSpace.SendAndReceive is probably unnecessary and could be causing some delays
Related
Hello can anyone tell me how to delete files using the API for TFS? Below is what I have but I can not get it to work any help would really be appreciated.
string[] InLocalDirectory = Directory.GetFiles(LogicAppConfig.Query(AppConfigLogic.TypeOfConfig.Path), "*", SearchOption.AllDirectories);
// Source Control
List<string> InSourceControl = new List<string>();
ItemSet SetOfItem = _ServerVersionControl.GetItems(_ServerPath, VersionSpec.Latest, RecursionType.Full);
foreach (Item GotItem in SetOfItem.Items)
{
ItemType TypeOfItem = GotItem.ItemType;
if (TypeOfItem == ItemType.File)
{
string LocalPath = _WorkspaceLocal.GetLocalItemForServerItem(GotItem.ServerItem);
InSourceControl.Add(LocalPath);
}
}
List<int> ToDeleteById = new List<int>();
foreach (string SourceFile in InSourceControl)
{
if (!IsIgnored(SourceFile) && !InLocalDirectory.Contains(SourceFile))
{
// Delete Source Control File
Item DeleteItem = _ServerVersionControl.GetItem(SourceFile);
ToDeleteById.Add(DeleteItem.ItemId);
// Update Local XML Directory
DataXml.Delete(SourceFile);
}
}
WorkItemStore wis = _CollectionTeamProject.GetService<WorkItemStore>();
wis.DestroyWorkItems(ToDeleteById);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Services.Common;
using Microsoft.VisualStudio.Services.Client;
using Microsoft.TeamFoundation.SourceControl.WebApi;
using Microsoft.VisualStudio.Services.WebApi;
namespace ConsoleAppX
{
class Program
{
static void Main(string[] args)
{
VssCredentials creds = new VssClientCredentials();
creds.Storage = new VssClientCredentialStorage();
VssConnection connection = new VssConnection(new Uri("https://tfsuri"), creds);
TfvcHttpClient tfvcClient = connection.GetClient<TfvcHttpClient>();
TfvcItem ti = tfvcClient.GetItemAsync("ProjectName", "$/FilePath","FileName").Result;
TfvcChange tchange = new TfvcChange(ti,VersionControlChangeType.Delete);
List<TfvcChange> change = new List<TfvcChange> { tchange };
TfvcChangeset tchangeset = new TfvcChangeset();
tchangeset.Changes = change;
tfvcClient.CreateChangesetAsync(tchangeset);
}
}
}
To delete a file, you need to use the VersionControlServer class to get an existing Workspace or create a new workspace. The workspace has a PendDelete method to create pending changes in the workspace. Then use the Workspace.Checkin method to commit them to source control:
https://msdn.microsoft.com/en-us/library/microsoft.teamfoundation.versioncontrol.client.workspace.aspx
I tried the penddelete before I tried the last way of doing it. But even when I manually go and delete a file and it hits the _WorkspaceLocal.PendDelete(SourceFile); line and is inserted for deletion it does not pick up on the line if (changes.Count() > 0) and then never check in.
string[] InLocalDirectory = Directory.GetFiles(LogicAppConfig.Query(AppConfigLogic.TypeOfConfig.Path), "*", SearchOption.AllDirectories);
// Source Control
List<string> InSourceControl = new List<string>();
ItemSet SetOfItem = _ServerVersionControl.GetItems(_ServerPath, VersionSpec.Latest, RecursionType.Full);
foreach (Item GotItem in SetOfItem.Items)
{
ItemType TypeOfItem = GotItem.ItemType;
if (TypeOfItem == ItemType.File)
{
string LocalPath = _WorkspaceLocal.GetLocalItemForServerItem(GotItem.ServerItem);
InSourceControl.Add(LocalPath);
}
}
List<int> ToDeleteById = new List<int>();
foreach (string SourceFile in InSourceControl)
{
if (!IsIgnored(SourceFile) && !InLocalDirectory.Contains(SourceFile))
{
// Delete Source Control File
Item DeleteItem = _ServerVersionControl.GetItem(SourceFile);
ToDeleteById.Add(DeleteItem.ItemId);
// Update Local XML Directory
DataXml.Delete(SourceFile);
// Set for Deletion
_WorkspaceLocal.PendDelete(SourceFile);
}
}
string ConflictMessage = "";
Conflict[] conflicts = _WorkspaceLocal.QueryConflicts(new string[] { _LocalPath }, true);
foreach (Conflict conflict in conflicts)
{
if (conflict != null)
{
try
{
if (conflict.CanMergeContent)
{
conflict.Resolution = Resolution.AcceptMerge;
}
else
{
conflict.Resolution = Resolution.AcceptYoursRenameTheirs;
}
ConflictMessage += #"\n\r\n\r" + conflict.GetFullMessage();
_WorkspaceLocal.ResolveConflict(conflict);
}
catch (Exception ex)
{
LogicAppConfig.Insert(AppConfigLogic.TypeOfConfig.Message, "Error Detected Previously:\r\n\r\n" + ex.Message + "\r\n\r\n" + ex.Source + "\r\n\r\n" + ex.StackTrace + "\r\n\r\n" + LogicAppConfig.Query(AppConfigLogic.TypeOfConfig.Path));
}
}
}
if (!String.IsNullOrEmpty(ConflictMessage))
{
LogicAppConfig.Insert(AppConfigLogic.TypeOfConfig.Message, ConflictMessage);
}
PendingChange[] changes = _WorkspaceLocal.GetPendingChanges();
if (changes.Count() > 0)
{
int ChangeSetId = _WorkspaceLocal.CheckIn(changes, _WorkspaceName + " Deleted by Member Collaboration Utility");
}
I have a document library in which we have added a custom folder content type in order to keep the Folder Owner in a custom field.
Now I am asked to set the default value of the "Add new" form to the Parent Folder Owner. I have tried this code below but the event fires after saving the new Folder. Could anyone pls help me? How can I set this default value before opening the form?
public override void ItemAdding(SPItemEventProperties properties)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
try
{
this.EventFiringEnabled = false;
base.ItemAdding(properties);
if (properties.List.RootFolder.Name == "Documents")
{
SPWeb web = properties.List.ParentWeb;
SPList List = properties.List;
SPField fld = List.Fields["Folder Owner"];
SPUser usr = web.CurrentUser;
SPFieldUserValue curUser = new SPFieldUserValue();
curUser.LookupId = usr.ID;
SPFolder parentFolder = web.GetFolder(properties.AfterUrl.Substring(0,properties.AfterUrl.LastIndexOf("/")));
if (parentFolder.Item["Folder Owner"] == null)
{
fld.DefaultValue = curUser.ToString();
}
else
{
fld.DefaultValue = parentFolder.Item["Folder Owner"].ToString();
}
fld.Update();
List.Update();
}
}
catch (Exception)
{
}
finally
{
this.EventFiringEnabled = true;
}
});
}
I would like to create sharepoint list items based on selected multiple files from local drive. After uploading selected multiple files list should contains new list items (title is file name) with attachments (one attachment/uploaded file).
Ok I extended my custom webpart (with dynatree) on that list using http://www.plupload.com/ and creating page for saving attachments.
public partial class ImportMultipleFilesAsListItems : LayoutsPageBase
{
protected void Page_Load(object sender, EventArgs e)
{
//request form parameters comes from plupload
int parentFolderKey = int.Parse(Request.Form["key"]);
var file = Request.Files[0];
SPList list = SPContext.Current.Web.GetList(Request.Form["listUrl"]);
SPListItem folderItem = list.GetItemById(parentFolderKey);
if (folderItem != null)
{
string parentFolder = null;
if (folderItem.Folder != null)
{
parentFolder = folderItem.Folder.Url;
}
else
{
int slashIndx = folderItem.Url.LastIndexOf('/');
parentFolder = folderItem.Url.Substring(0, slashIndx);
}
SPListItem childFile = list.AddItem(parentFolder, SPFileSystemObjectType.File);
childFile["Title"] = file.FileName;
childFile["IsFolder"] = 0;
childFile["DocParentId"] = parentFolderKey;
childFile.UpdateOverwriteVersion();
byte[] data = new byte[file.ContentLength];
file.InputStream.Read(data, 0, file.ContentLength);
childFile.Attachments.AddNow(file.FileName, data);
}
}
}
$(function () {
var listInfo = new Object();
listInfo.key = null;
listInfo.listUrl = ctx.listUrlDir;
listInfo.__REQUESTDIGEST = $('#__REQUESTDIGEST').val();
$("#uploader").pluploadQueue({
// General settings
runtimes: 'browserplus,html5,html4',
url: $('#uploadMultipleFilesUrl').val(),
max_file_size: '50mb',
chunk_size: '1mb',
multipart_params: listInfo,
rename: true
});
// Client side form validation
$('form').submit(function (e) {
var uploader = $('#uploader').pluploadQueue();
// Files in queue upload them first
if (uploader.files.length > 0) {
// When all files are uploaded submit form
uploader.bind('StateChanged', function () {
if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
$('form')[0].submit();
}
});
uploader.start();
} else {
alert('You must queue at least one file.');
}
return false;
});
$("#uploader").hide();
});
Is there any way of set a Nintex Flexi task completion through Sharepoint's web services? We have tried updating the "WorkflowOutcome", "ApproverComments" and "Status" fields without success (actually the comments and status are successfully updated, however I can find no way of updating the WorkflowOutcome system field).
I can't use the Nintex Web service (ProcessTaskResponse) because it needs the task's assigned user's credentials (login, password, domain).
The Asp.net page doesn't have that information, it has only the Sharepoint Administrator credentials.
One way is to delegate the task to the admin first, and then call ProcessTaskResponse, but it isn't efficient and is prone to errors.
In my tests so far, any update (UpdateListItems) to the WorkflowOutcome field automatically set the Status field to "Completed" and the PercentComplete field to "1" (100%), ending the task (and continuing the flow), but with the wrong answer: always "Reject", no matter what I try to set it to.
Did you try this code: (try-cacth block with redirection does the trick)
\\set to actual outcome id here, for ex. from OutComePanel control
taskItem[Nintex.Workflow.Common.NWSharePointObjects.FieldDecision] = 0;
taskItem[Nintex.Workflow.Common.NWSharePointObjects.FieldComments] = " Some Comments";
taskItem.Update();
try
{
Nintex.Workflow.Utility.RedirectOrCloseDialog(HttpContext.Current, Web.Url);
}
catch
{
}
?
Here are my code to change outcome of nintex flexi task. My problem is permission. I had passed admin token to site. It's solve the problem.
var siteUrl = "...";
using (var tempSite = new SPSite(siteUrl))
{
var sysToken = tempSite.SystemAccount.UserToken;
using (var site = new SPSite(siteUrl, sysToken))
{
var web = site.OpenWeb();
...
var cancelled = "Cancelled";
task.Web.AllowUnsafeUpdates = true;
Hashtable ht = new Hashtable();
ht[SPBuiltInFieldId.TaskStatus] = SPResource.GetString(new CultureInfo((int)task.Web.Language, false), Strings.WorkflowStatusCompleted, new object[0]);
ht["Completed"] = true;
ht["PercentComplete"] = 1;
ht["Status"] = "Completed";
ht["WorkflowOutcome"] = cancelled;
ht["Decision"] = CommonHelper.GetFlexiTaskOutcomeId(task, cancelled);
ht["ApproverComments"] = "cancelled";
CommonHelper.AlterTask((task as SPListItem), ht, true, 5, 100);
task.Web.AllowUnsafeUpdates = false;
}
}
}
}
}
}
public static string GetFlexiTaskOutcomeId(Microsoft.SharePoint.Workflow.SPWorkflowTask task, string outcome)
{
if (task["MultiOutcomeTaskInfo"] == null)
{
return string.Empty;
}
string xmlOutcome = HttpUtility.HtmlDecode(task["MultiOutcomeTaskInfo"].ToString());
if (string.IsNullOrEmpty(xmlOutcome))
{
return string.Empty;
}
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlOutcome);
var node = doc.SelectSingleNode(string.Format("/MultiOutcomeResponseInfo/AvailableOutcomes/ConfiguredOutcome[#Name='{0}']", outcome));
return node.Attributes["Id"].Value;
}
public static bool AlterTask(SPListItem task, Hashtable htData, bool fSynchronous, int attempts, int milisecondsTimeout)
{
if ((int)task[SPBuiltInFieldId.WorkflowVersion] != 1)
{
SPList parentList = task.ParentList.ParentWeb.Lists[new Guid(task[SPBuiltInFieldId.WorkflowListId].ToString())];
SPListItem parentItem = parentList.Items.GetItemById((int)task[SPBuiltInFieldId.WorkflowItemId]);
for (int i = 0; i < attempts; i++)
{
SPWorkflow workflow = parentItem.Workflows[new Guid(task[SPBuiltInFieldId.WorkflowInstanceID].ToString())];
if (!workflow.IsLocked)
{
task[SPBuiltInFieldId.WorkflowVersion] = 1;
task.SystemUpdate();
break;
}
if (i != attempts - 1)
{
Thread.Sleep(milisecondsTimeout);
}
}
}
var result = SPWorkflowTask.AlterTask(task, htData, fSynchronous);
return result;
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
recently I started a task to retrieve the emails on the exchange server using javamail API. However, sometimes I can not fetch any mails because outlook client synchronises with the mail server and those emails are therefore removed from the server.
Is there any way to ensure that I can fetch all new emails no matter before or after outlook synchronization. Or I should try to connect to outlook, if so, is there any available free API? Thank you.
Isn't is possible to configure outlook to leave a copy of the messages on the server? I really do not think connection to outlook is the way to go.
I have the solution to read emails from outlook.
We need to give username, password, domain and exchange address: https://webmail.**companynameXYZ**.com/ews/exchange.asmx.
following is the code .... I have used this from some purpose, to download attachments from undread mails and making it as read after downloading.
NOTE: we need DLL Microsoft.Exchange.WebServices.dll to be downloaded
CODE in C#:
string _username = string.Empty;
string _password = string.Empty;
string _domain = "us";
string _exchange = string.Empty;
_username = ConfigurationSettings.AppSettings["Username"].ToString();
_password = ConfigurationSettings.AppSettings["Pasword"].ToString();
_exchange = ConfigurationSettings.AppSettings["MailServer"].ToString();
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
// service.AutodiscoverUrl("maxdatafeeds#maritz.com");
service.Url = new Uri(_exchange);
service.Credentials = new WebCredentials(_username, _password, _domain);
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(10));
int attachmentCount = 0;
foreach (Item item in findResults.Items)
{
// Bind to an existing message item, requesting its Id property plus its attachments collection.
EmailMessage message = EmailMessage.Bind(service, item.Id);
//read only unread mails and has attachemnts to it.
if ((!message.IsRead) && message.HasAttachments )
{
Console.WriteLine(item.Subject);
#region Iterate through the attachments collection and load each attachment.
foreach (Microsoft.Exchange.WebServices.Data.Attachment attachment in message.Attachments)
{
if (attachment is FileAttachment)
{
FileAttachment fileAttachment = attachment as FileAttachment;
attachmentCount++;
// Load the file attachment into memory and print out its file name.
fileAttachment.Load();
Console.WriteLine("Attachment name: " + fileAttachment.Name);
//create Attachments-folder if not exists.
if (!Directory.Exists(#"C:\Attachments\"))
{
Directory.CreateDirectory(#"C:\Attachments\");
}
// Load attachment contents into a file.
fileAttachment.Load("C:\\attachments\\" + fileAttachment.Name);
}
else // Attachment is an item attachment.
{
// Load attachment into memory and write out the subject.
ItemAttachment itemAttachment = attachment as ItemAttachment;
itemAttachment.Load();
Console.WriteLine("Subject: " + itemAttachment.Item.Subject);
}
}//for inner
#endregion
//mark as READ
message.IsRead = true;
message.Update(ConflictResolutionMode.AlwaysOverwrite);
Console.WriteLine("------------------------");
}//if
}//for outer
Microsoft team has created EWS-Java-Api (a java implementation) as an alternative to Microsoft.Exchange.WebServices.dll for C# implementation, and nice thing is its open sourced:
Link: https://github.com/OfficeDev/ews-java-api/wiki
JAVA Code:
package EWSGetDetailsOffice365;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import microsoft.exchange.webservices.data.Appointment;
import microsoft.exchange.webservices.data.AppointmentSchema;
import microsoft.exchange.webservices.data.CalendarFolder;
import microsoft.exchange.webservices.data.CalendarView;
import microsoft.exchange.webservices.data.EmailMessage;
import microsoft.exchange.webservices.data.ExchangeService;
import microsoft.exchange.webservices.data.ExchangeVersion;
import microsoft.exchange.webservices.data.FindItemsResults;
import microsoft.exchange.webservices.data.Folder;
import microsoft.exchange.webservices.data.IAutodiscoverRedirectionUrl;
import microsoft.exchange.webservices.data.Item;
import microsoft.exchange.webservices.data.ItemId;
import microsoft.exchange.webservices.data.ItemSchema;
import microsoft.exchange.webservices.data.ItemView;
import microsoft.exchange.webservices.data.PropertySet;
import microsoft.exchange.webservices.data.SearchFilter;
import microsoft.exchange.webservices.data.ServiceLocalException;
import microsoft.exchange.webservices.data.WebCredentials;
import microsoft.exchange.webservices.data.WellKnownFolderName;
public class MSExchangeEmailService {
public static class RedirectionUrlCallback implements IAutodiscoverRedirectionUrl {
public boolean autodiscoverRedirectionUrlValidationCallback(String redirectionUrl) {
return redirectionUrl.toLowerCase().startsWith("https://");
}
}
private static ExchangeService service;
private static Integer NUMBER_EMAILS_FETCH =5; // only latest 5 emails/appointments are fetched.
/**
* Firstly check, whether "https://webmail.xxxx.com/ews/Services.wsdl" and "https://webmail.xxxx.com/ews/Exchange.asmx"
* is accessible, if yes that means the Exchange Webservice is enabled on your MS Exchange.
*/
static{
try{
service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
//service.setUrl(new URI("https://webmail.xxxx.com/ews/Exchange.asmx"));
}catch (Exception e) {
e.printStackTrace();
}
}
/**
* Initialize the Exchange Credentials.
* Don't forget to replace the "USRNAME","PWD","DOMAIN_NAME" variables.
*/
public MSExchangeEmailService() {
service.setCredentials(new WebCredentials("abc#domain.com", "1234"));
try {
service.autodiscoverUrl("dhananjayk#sysmind.com", new RedirectionUrlCallback());
} catch (Exception ex) {
Logger.getLogger(MSExchangeEmailService.class.getName()).log(Level.SEVERE, null, ex);
}
service.setTraceEnabled(true);
}
/**
* Reading one email at a time. Using Item ID of the email.
* Creating a message data map as a return value.
*/
public Map readEmailItem(ItemId itemId){
Map messageData = new HashMap();
try{
Item itm = Item.bind(service, itemId, PropertySet.FirstClassProperties);
EmailMessage emailMessage = EmailMessage.bind(service, itm.getId());
messageData.put("emailItemId", emailMessage.getId().toString());
messageData.put("subject", emailMessage.getSubject().toString());
messageData.put("fromAddress",emailMessage.getFrom().getAddress().toString());
messageData.put("senderName",emailMessage.getSender().getName().toString());
Date dateTimeCreated = emailMessage.getDateTimeCreated();
messageData.put("SendDate",dateTimeCreated.toString());
Date dateTimeRecieved = emailMessage.getDateTimeReceived();
messageData.put("RecievedDate",dateTimeRecieved.toString());
messageData.put("Size",emailMessage.getSize()+"");
messageData.put("emailBody",emailMessage.getBody().toString());
}catch (Exception e) {
e.printStackTrace();
}
return messageData;
}
/**
* Number of email we want to read is defined as NUMBER_EMAILS_FETCH,
*/
public List readEmails(){
List msgDataList = new ArrayList();
try{
Folder folder = Folder.bind( service, WellKnownFolderName.Inbox );
FindItemsResults<Item> results = service.findItems(folder.getId(), new ItemView(NUMBER_EMAILS_FETCH));
int i =1;
for (Item item : results){
Map messageData = new HashMap();
messageData = readEmailItem(item.getId());
System.out.println("\nEmails #" + (i++ ) + ":" );
System.out.println("subject : " + messageData.get("subject").toString());
System.out.println("Sender : " + messageData.get("senderName").toString());
msgDataList.add(messageData);
}
}catch (Exception e) {
e.printStackTrace();
}
return msgDataList;
}
/**
* Reading one appointment at a time. Using Appointment ID of the email.
* Creating a message data map as a return value.
*/
public Map readAppointment(Appointment appointment){
Map appointmentData = new HashMap();
try {
appointmentData.put("appointmentItemId", appointment.getId().toString());
appointmentData.put("appointmentSubject", appointment.getSubject());
appointmentData.put("appointmentStartTime", appointment.getStart()+"");
appointmentData.put("appointmentEndTime", appointment.getEnd()+"");
//appointmentData.put("appointmentBody", appointment.getBody().toString());
} catch (ServiceLocalException e) {
e.printStackTrace();
}
return appointmentData;
}
/**
*Number of Appointments we want to read is defined as NUMBER_EMAILS_FETCH,
* Here I also considered the start data and end date which is a 30 day span.
* We need to set the CalendarView property depending upon the need of ours.
*/
public List readAppointments(){
List apntmtDataList = new ArrayList();
Calendar now = Calendar.getInstance();
Date startDate = Calendar.getInstance().getTime();
now.add(Calendar.DATE, 30);
Date endDate = now.getTime();
try{
CalendarFolder calendarFolder = CalendarFolder.bind(service, WellKnownFolderName.Calendar, new PropertySet());
CalendarView cView = new CalendarView(startDate, endDate, 5);
cView.setPropertySet(new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End));// we can set other properties as well depending upon our need.
//FindItemsResults appointments = calendarFolder.findAppointments(cView);
FindItemsResults<Appointment> appointments = calendarFolder.findAppointments(cView);
System.out.println("|------------------> Appointment count = " + appointments.getTotalCount());
int i =1;
//List appList = appointments.getItems();
for (Appointment appointment : appointments.getItems()) {
System.out.println("\nAPPOINTMENT #" + (i++ ) + ":" );
Map appointmentData = new HashMap();
appointmentData = readAppointment(appointment);
System.out.println("subject : " + appointmentData.get("appointmentSubject").toString());
System.out.println("On : " + appointmentData.get("appointmentStartTime").toString());
apntmtDataList.add(appointmentData);
}
}catch (Exception e) {
e.printStackTrace();
}
return apntmtDataList;
}
public static void getAllMeetings() throws Exception {
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = formatter.parse("2016-01-01 00:00:00");
SearchFilter filter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.LastModifiedTime,startDate);
FindItemsResults<Item> findResults = service.findItems(WellKnownFolderName.Calendar, filter, new ItemView(1000));
System.out.println("|------------------> meetings count = " + findResults.getTotalCount());
for (Item item : findResults.getItems())
{
Appointment appt = (Appointment)item;
//appt.setStartTimeZone();
System.out.println("TimeZone====="+appt.getTimeZone());
System.out.println("SUBJECT====="+appt.getSubject());
System.out.println("Location========"+appt.getLocation());
System.out.println("Start Time========"+appt.getStart());
System.out.println("End Time========"+appt.getEnd());
System.out.println("Email Address========"+ appt.getOrganizer().getAddress());
System.out.println("Last Modified Time========"+appt.getLastModifiedTime());
System.out.println("Last Modified Time========"+appt.getLastModifiedName());
System.out.println("*************************************************\n");
}
} catch (Exception exp) {
exp.printStackTrace();
}
}
public static void main(String[] args) {
MSExchangeEmailService msees = new MSExchangeEmailService();
//msees.readEmails();
//msees.readAppointments();
try {
msees.getAllMeetings();
} catch (Exception ex) {
Logger.getLogger(MSExchangeEmailService.class.getName()).log(Level.SEVERE, null, ex);
}
}
}