Sample code for 30+ languages & platforms
Pascal (Lazarus/Delphi)

Save an IMAP Attachment to a File

See more IMAP Examples

Demonstrates the Chilkat Imap.FetchAttachment method, which downloads one attachment from the IMAP server and saves it to the filesystem. The first argument is the Email, the second is the zero-based attachment index, and the third is the file path to write. This example fetches a message headers-only, inspects its attachments without downloading them, and then downloads a specific attachment on demand.

Note: The output path is relative to the application's current working directory. Chilkat does not create missing parent directories, so qa_output/ must already exist.

Background: This is the method's real value. A headers-only fetch downloads no attachment bodies, yet methods such as GetMailNumAttach and GetMailAttachFilename still work from the ckx-imap-* metadata. FetchAttachment then uses that metadata to download just the requested MIME part from the server — even in a later session. A client can therefore list messages and their attachment names cheaply and pull individual attachments only when the user actually wants them, instead of downloading every full message. (If the Email already holds the attachment bytes, they are saved without contacting the server.)

Chilkat Pascal (Lazarus/Delphi) Downloads

Pascal (Lazarus/Delphi)
program ChilkatDemo;

// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}

uses
  {$IFDEF UNIX}
  cthreads,
  {$ENDIF}
  SysUtils,
  CkDllLoader,
  Chilkat.StringBuilder,
  Chilkat.Imap,
  Chilkat.Email;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  success: Boolean;
  imap: TImap;
  headersOnly: Boolean;
  useUid: Boolean;
  seqNum: Integer;
  email: TEmail;
  numAttach: Integer;
  fname: string;
  sbPath: TStringBuilder;
  savePath: string;

begin
  success := False;

  //  Demonstrates the Imap.FetchAttachment method, which downloads one attachment from the IMAP
  //  server and saves it to a file.  The 1st argument is the Email, the 2nd is the zero-based
  //  attachment index, and the 3rd is the file path to write.
  //  
  //  The compelling use case: fetch a message headers-only, inspect its attachments without
  //  downloading them, and then download just the attachment(s) you want.

  imap := TImap.Create;

  imap.Ssl := True;
  imap.Port := 993;

  success := imap.Connect('imap.example.com');
  if (success = False) then
    begin
      WriteLn(imap.LastErrorText);
      Exit;
    end;
  success := imap.Login('user@example.com','myPassword');
  if (success = False) then
    begin
      WriteLn(imap.LastErrorText);
      Exit;
    end;

  success := imap.SelectMailbox('Inbox');
  if (success = False) then
    begin
      WriteLn(imap.LastErrorText);
      Exit;
    end;

  //  Fetch only the message headers.  Attachment bodies are NOT downloaded, but the ckx-imap-*
  //  metadata describing the attachments is present, so the attachment info methods still work.
  headersOnly := True;
  useUid := False;
  seqNum := 1;
  email := TEmail.Create;
  success := imap.FetchEmail(headersOnly,seqNum,useUid,email);
  if (success = False) then
    begin
      WriteLn(imap.LastErrorText);
      Exit;
    end;

  //  Even though the body was not downloaded, the attachment count and names are available.
  numAttach := imap.GetMailNumAttach(email);
  WriteLn('Attachments: ' + numAttach);

  if (numAttach > 0) then
    begin
      //  Get the attachment's original filename and use it for the saved file.
      fname := imap.GetMailAttachFilename(email,0);
      if (imap.LastMethodSuccess = False) then
        begin
          WriteLn(imap.LastErrorText);
          Exit;
        end;

      //  Build the output path "qa_output/<filename>".
      sbPath := TStringBuilder.Create;
      sbPath.Append('qa_output/');
      sbPath.Append(fname);
      savePath := sbPath.GetAsString();

      //  Download just the first attachment (index 0) from the server and save it to that path.
      success := imap.FetchAttachment(email,0,savePath);
      if (success = False) then
        begin
          WriteLn(imap.LastErrorText);
          Exit;
        end;
      WriteLn('Saved attachment: ' + savePath);
    end;

  success := imap.Disconnect();
  if (success = False) then
    begin
      WriteLn(imap.LastErrorText);
      Exit;
    end;


  imap.Free;
  email.Free;
      sbPath.Free;

end;

// ---------------------------------------------------------------------------

begin

  try
    RunDemo;
  except
    on E: Exception do
      WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
  end;

  WriteLn;
  {$IFDEF MSWINDOWS}
  WriteLn('Press Enter to exit...');
  ReadLn;
  {$ENDIF}
end.