Search code examples
delphioutlookmailing

Creating a mail with attachment in Outlook and displaying it


I want to create a mail with attachment in Outlook and display it before sending it, but I think I have tried almost every sample I have found on the net without any luck. I could use Indy, but I would very much like to use Outlook to be sure that the mail is proper because it is for business use.

Any input for a function that takes Address, subject, message and attachment as parameters and then displays the message in Outlook before sending it.


Solution

  • See MailItem.Display Method.

    uses
      comobj;
    
    ..
    
    procedure DisplayMail(Address, Subject, Body: string; Attachment: TFileName);
    var
      Outlook: OleVariant;
      Mail: Variant;
    const
      olMailItem = $00000000;
    begin
      try
        Outlook := GetActiveOleObject('Outlook.Application');
      except
        Outlook := CreateOleObject('Outlook.Application');
      end;
      Mail := Outlook.CreateItem(olMailItem);
      Mail.To := Address;
      Mail.Subject := Subject;
      Mail.Body := Body;
      if Attachment <> '' then
        Mail.Attachments.Add(Attachment);
      Mail.Display;
    end;
    
    procedure TForm1.Button1Click(Sender: TObject);
    begin
      DisplayMail('mailaddress', 'subject', 'message', 'attachmentfile');
    end;