Search code examples
emaildelphioutlookole

Outlook new message does not work after switching to office365


We have the following function in our application which opens a new message in outlook so the user can send an email via Outlook.

program SO_37131815;
{$APPTYPE CONSOLE}

uses
  Classes, ActiveX, ComObj, Variants, SysUtils;

procedure OutlookMail(ToAddress, Subject: string);
var
  OutlookProgram: OLEVariant;
  MailItem: Variant;
begin
  try
    OutlookProgram := GetActiveOleObject('Outlook.Application');
  except
    OutlookProgram := CreateOleObject('Outlook.Application');
  end;

  MailItem := OutlookProgram.CreateItem(0);

  if ToAddress = '' then begin
    ToAddress := ' ';
  end;
  MailItem.Recipients.Add(ToAddress);
  MailItem.Subject := Subject;

  try
    MailItem.Display(False); //.Display(Modal)
  except
    //don't worry...
  end;

  OutlookProgram := Unassigned;
end;

begin
  CoInitialize(nil);
  OutlookMail('', 'blah');
end.

it's all greek to me

This worked fine for years...since a couple of days ago when the client switched to Office365. When a new message is created from outlook it works fine, when it's created from our application it cannot send the message.

In outlook 2010 the error message is: "Could not complete the operation. One or more parameter values are not valid."

In outlook 2016 the error message is: "Sorry something went wrong. You may want to try again". outlook 2016 error

I also noticed that when the new message is created from our application it cannot be saved to drafts and it throws the same errors.

The procedure opens the new message window but when Send Mail is pressed, Outlook cannot send it. What can I do, to fix this? Do I need to set some property before Display is called?

UPDATE: Thanks to David persistency I've narrowed it down. Outlook produces error when the ToAddress parameter is empty (or space). So adding the following code seems to fix the problem.

if Trim(ToAddress) <> '' then begin
  MailItem.Recipients.Add(ToAddress);
end;

Does anyone have a better idea?


Solution

  • When ToAddress argument is empty, You should not pass a space (or empty string) parameter to MailItem.Recipients.Add method.

    So the solution is to avoid the above:

    if Trim(ToAddress) <> '' then
      MailItem.Recipients.Add(ToAddress);