0

I'm on Delphi 11.

I need to create a new instance of a TIdMessage and TIDSmtp, simply by copying all properties from another TIdMessage and TIDSmtp. What's the best way to do it besides manually assigning the properties you need one by one?

var 
  newIdMessage : TIDMessage;
  newIDSmtp : TIDSmtp;
begin
  newIdMessage := TIDMessage.create;
  newIdSmtp := TIDSmtp.create;

  // something like this:
  newIdMessage.copyPropertiesFrom(form1.IdMessage1);
  newIdSmtp.copyPropertiesFrom(form1.IdSmtp1);
end;
AmigoJack
  • 5,234
  • 1
  • 15
  • 31
delphirules
  • 6,443
  • 17
  • 59
  • 108
  • Create an instance of TIdMessageClient and use the ProcessMessage method – Dave Nottage May 10 '22 at 23:43
  • 1
    @DaveNottage I don't understand how that answers the question. `TIdMessageClient.ProcessMessage()` is intended for reading an email from a file/socket, not for cloning objects in memory. – Remy Lebeau May 11 '22 at 02:06
  • 1
    @delphirules like most Delphi objects, most Indy components do not directly support cloning themselves (ie, by overriding `TPersistent.Assign/To()`), so you have to copy their properties one at a time, either manually or via RTTI. For `published` properties, at least, the simplest solution is to use a `TMemoryStream` with its `WriteComponent()` and `ReadComponent()` methods to save an object to an in-memory DFM and then read it back out into another object. Other solutions exist, but they require more work. – Remy Lebeau May 11 '22 at 02:19
  • @RemyLebeau It's the same process that TIdMessage uses for LoadFromStream – Dave Nottage May 11 '22 at 02:22
  • 1
    @DaveNottage only because `TIdMessage`'s logic is not implemented in the right place. The logic is in `TIdMessageClient` which is a base class of the SMTP/POP3/IMAP components. `TIdMessage` creates a temp `TIdMessageClient` to read/write emails via a stream/file. But I still wouldn't suggest your solution. You didn't explain how to create the data that `ProcessMessage()` would read. It would be far easier to just use `TIdMessage.SaveToStream()` and `TIdMessage.LoadFromStream()` instead, but that is not a true clone of all of the properties. And, you can't duplicate `TIdSMTP` that way anyway. – Remy Lebeau May 11 '22 at 02:36
  • 1
    :) Funny title now: `How to duplicate an object? [duplicate]` – AmigoJack May 11 '22 at 14:01
  • @AmigoJack Inception ! – delphirules May 11 '22 at 17:23

0 Answers0