1

I need help resolving an issue with my code for adding Outlook Tasks. It is functioning correctly on some systems, but not on a machine with Office 365 installed. Specifically, when Outlook is already open on this machine, my code produces an error. However, when Outlook is closed, the code works correctly. What steps can I take to resolve this issue?

image

procedure CreateOutlookReminder(const Subject, Body, Location: string;
  const Start, Duration: TDateTime;
  const ReminderMinutesBeforeStart: Integer);
var
  Outlook, Calendar, AppointmentItem: OleVariant;
begin
  // Connect to Outlook
  try
    try
      Outlook := GetActiveOleObject('Outlook.Application');
    except
      Outlook := CreateOleObject('Outlook.Application');
    end
  Except
    on E: Exception do
    begin
      MessageDlg('Unable to add reminder.' + #13#10 +
        'The version of outlook on your machine is either unsupported or it does not exist.'
        + E.Message, mtError, [mbOK], 0);
      Exit
    end;
  end;
  Calendar := Outlook.GetNamespace('MAPI').GetDefaultFolder(13);
  // olFolderCalendar

  // Create the Task
  AppointmentItem := Calendar.Items.Add; // Task
  AppointmentItem.Subject := Subject;
  AppointmentItem.Body := Body;
  AppointmentItem.remindertime := formatdatetime('mm/dd/yy h:nn:ss ampm',
    Duration);
  AppointmentItem.duedate := Duration;
  // Set the reminder
  AppointmentItem.ReminderSet := True;
  // Save and display the appointment
  AppointmentItem.Save;
  Outlook := unAssigned;
end;
Ken White
  • 123,280
  • 14
  • 225
  • 444

2 Answers2

3

Make sure your code is not running with elevated privileges - Outlook is a singleton, so when you call CreateOleObject (there is no reason to ever call GetActiveOleObject for Outlook), it returns a pointer to the already running instance. If Outlook and your code are running in different security contexts (e.g., one is running as "Run As Administrator"), the COM system will refuse to marshal the calls.

Dmitry Streblechenko
  • 62,942
  • 4
  • 53
  • 78
2

when Outlook is already open on this machine, my code produces an error.

Make sure that you run your application under the same security context in Windows. That means if one of applications is under with administrator privileges (elevated) the other should be run with administrator privileges as well (Run As Administrator). Otherwise, both applications will not find each other.

Another factor is that you can't create a new Outlook Application instance on the system if one is already running. That means if you have got an instance running under a different security context you can't connect to it or create a new Application instance.

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45