Sample code for 30+ languages & platforms
Delphi DLL

Get IMAP Attachment Filenames

See more IMAP Examples

Demonstrates the Chilkat Imap.GetMailAttachFilename method, which returns the filename of an attachment. The first argument is the Email and the second is the zero-based attachment index. This example fetches only the message headers and lists the attachment filenames.

Background: This method reads the filename from ckx-imap-* metadata, so it works on a header-only email even though the attachment bodies have not been downloaded. That is exactly what a mail client needs to render the paperclip list — the names of the attached files — before the user decides to download any of them.

Chilkat Delphi DLL Downloads

Delphi DLL
var
success: Boolean;
imap: HCkImap;
headersOnly: Boolean;
useUid: Boolean;
seqNum: Integer;
email: HCkEmail;
numAttach: Integer;
i: Integer;
fname: PWideChar;

begin
success := False;

//  Demonstrates the Imap.GetMailAttachFilename method, which returns the filename of an
//  attachment.  The 1st argument is the Email and the 2nd is the zero-based attachment index.

imap := CkImap_Create();

CkImap_putSsl(imap,True);
CkImap_putPort(imap,993);

success := CkImap_Connect(imap,'imap.example.com');
if (success = False) then
  begin
    Memo1.Lines.Add(CkImap__lastErrorText(imap));
    Exit;
  end;
success := CkImap_Login(imap,'user@example.com','myPassword');
if (success = False) then
  begin
    Memo1.Lines.Add(CkImap__lastErrorText(imap));
    Exit;
  end;

success := CkImap_SelectMailbox(imap,'Inbox');
if (success = False) then
  begin
    Memo1.Lines.Add(CkImap__lastErrorText(imap));
    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 := CkEmail_Create();
success := CkImap_FetchEmail(imap,headersOnly,seqNum,useUid,email);
if (success = False) then
  begin
    Memo1.Lines.Add(CkImap__lastErrorText(imap));
    Exit;
  end;

//  Loop over the attachments and print each filename.
numAttach := CkImap_GetMailNumAttach(imap,email);
Memo1.Lines.Add('Attachments: ' + IntToStr(numAttach));

for i := 0 to numAttach - 1 do
  begin
    //  GetMailAttachFilename returns a string, so assign it to a string variable.
    fname := CkImap__getMailAttachFilename(imap,email,i);
    if (CkImap_getLastMethodSuccess(imap) = False) then
      begin
        Memo1.Lines.Add(CkImap__lastErrorText(imap));
        Exit;
      end;
    Memo1.Lines.Add(fname);
  end;

success := CkImap_Disconnect(imap);
if (success = False) then
  begin
    Memo1.Lines.Add(CkImap__lastErrorText(imap));
    Exit;
  end;

CkImap_Dispose(imap);
CkEmail_Dispose(email);