Search code examples
delphiemailpop3indy10

Send email with some [text] files with TIdPOP3Server


I have no problems sending a text file via the OnRetrieve event of TIdPOP3Server in indy 10, but I don't know how to send multiple files. I see with SMTP it is achieved with TIdAttachment to the TIdMessage, but how to send TIdAttachment from my TIdPOP3Server.OnRetrieve event to my POP3 client who can then read the sent files like this :

if MsgDecode.MessageParts[i] Is TIdAttachment then begin
  (MsgDecode.MessageParts[i] as TIdAttachment).SaveToFile((MsgDecode.MessageParts[j] as TIdAttachment).FileName);

Can anyone help me with this issue ?

This is my OnRetrieve event :

procedure POP3ServerRetrieve(aCmd: TIdCommand; AMsgNo: Integer); 
If (AMsgNO >= 1) AND (AMsgNo<=myMailsCount) then begin 
aCmd.SendReply; 
aCmd.Response.LoadFromFile('mail_filename'); 
aCmd.Response.LoadFromFile('mail_attachment_filename_1'); 
// ... loading N attachments 
end 
Else aCmd.Reply.SetReply(ERR,Format(' -Message %d Does not exist.',[AMsgNO])); 

Solution

  • Try this instead:

    procedure POP3ServerRetrieve(aCmd: TIdCommand; AMsgNo: Integer); 
    var
      Msg: TIdMessage;
      Stream: TMemoryStream;
    begin
      if (AMsgNO >= 1) AND (AMsgNo <= myMailsCount) then
      begin 
        Stream := TMemoryStream.Create;
        try
          Msg := TIdMessage.Create;
          try
            // fill Msg as needed ...
            Msg.SaveToStream(Stream);
          finally
            Msg.Free;
          end;
          aCmd.Reply.SetReply(OK, 'message follows');
          aCmd.SendReply; 
          aCmd.Connection.IOHandler.Write(Stream);
        finally
          Stream.Free;
        end;
      end 
      else
        aCmd.Reply.SetReply(ERR, Format('Message %d Does not exist.', [AMsgNO])); 
    end;