Pascal (Lazarus/Delphi)
Pascal (Lazarus/Delphi)
Save All MIME Attachments to Files
See more MIME Examples
Demonstrates the Chilkat Mime.PartsToFiles method, which recursively traverses the MIME tree and saves each part having a nonempty filename parameter to a directory. The first argument is the destination directory and the second is a StringTable that receives the saved filenames.
Note: The file paths are relative to the application's current working directory. Absolute paths may also be used. Supply the paths appropriate to your own environment.
Background: This extracts every named attachment from a message in one call, walking the whole tree so it finds attachments nested inside multipart containers. It saves only parts that declare a
filename — inline body parts without one are skipped — and reports what it wrote via the StringTable, which is handy for logging or follow-up processing. The destination directory must already exist.Chilkat Pascal (Lazarus/Delphi) Downloads
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.Mime,
Chilkat.StringTable;
// ---------------------------------------------------------------------------
procedure RunDemo;
var
success: Boolean;
mime: TMime;
savedFiles: TStringTable;
n: Integer;
i: Integer;
name: string;
begin
success := False;
mime := TMime.Create;
success := mime.LoadMimeFile('qa_data/multipart_message.eml');
if (success = False) then
begin
WriteLn(mime.LastErrorText);
Exit;
end;
// Recursively traverse the MIME tree and save each part that has a nonempty "filename" parameter
// to a directory. The 1st argument is the destination directory and the 2nd is a StringTable
// that receives the saved filenames.
savedFiles := TStringTable.Create;
success := mime.PartsToFiles('qa_output/attachments',savedFiles);
if (success = False) then
begin
WriteLn(mime.LastErrorText);
Exit;
end;
n := savedFiles.Count;
WriteLn('Saved ' + n + ' files:');
for i := 0 to n - 1 do
begin
name := savedFiles.StringAt(i);
if (savedFiles.LastMethodSuccess = False) then
begin
WriteLn(savedFiles.LastErrorText);
Exit;
end;
WriteLn(name);
end;
mime.Free;
savedFiles.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.