Sample code for 30+ languages & platforms
Lazarus Pascal

Set a MIME Header Field

See more MIME Examples

Demonstrates the Chilkat Mime.SetHeaderField method, which sets a single header field. The first argument is the field name and the second is the value. All existing occurrences are removed and one replacement is inserted, or a new field is added if none exists.

Background: For headers that should appear exactly once — Subject, From, Content-Type — this is the method to use, because it guarantees a single occurrence no matter how many times you call it. That idempotence is the key difference from AddHeaderField, which would leave duplicates behind. Setting an empty value removes the field.

Chilkat Lazarus Pascal Downloads

Lazarus Pascal
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;

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

procedure RunDemo;
var
  success: Boolean;
  mime: TMime;
  subject: string;

begin
  success := False;

  //  Demonstrates the Mime.SetHeaderField method, which sets a single header field.  The 1st argument
  //  is the field name and the 2nd is the value.  All existing occurrences are removed and one
  //  replacement is inserted (or a new field is added if none exists).

  mime := TMime.Create;

  success := mime.SetBodyFromPlainText('Hello.');
  if (success = False) then
    begin
      WriteLn(mime.LastErrorText);
      Exit;
    end;

  //  Unlike AddHeaderField, SetHeaderField ensures exactly one field with this name.
  success := mime.SetHeaderField('Subject','Weekly Report');
  if (success = False) then
    begin
      WriteLn(mime.LastErrorText);
      Exit;
    end;

  //  Setting it again replaces the previous value rather than adding a duplicate.
  success := mime.SetHeaderField('Subject','Weekly Report (revised)');
  if (success = False) then
    begin
      WriteLn(mime.LastErrorText);
      Exit;
    end;

  subject := mime.GetHeaderField('Subject');
  if (mime.LastMethodSuccess = False) then
    begin
      WriteLn(mime.LastErrorText);
      Exit;
    end;
  WriteLn('Subject: ' + subject);


  mime.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.