Sample code for 30+ languages & platforms
Lazarus Pascal

Amazon SES v2: Create and preview a receipt template

See more Amazon SES Examples

Create the regional OrderReceipt template once. Set createTemplate to false to preview it with sample order data. To exercise the missing-field case, omit orderNumber from the preview data and inspect the rendering error. A successful preview returns MIME content without sending a message.

CreateEmailTemplate · TestRenderEmailTemplate

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.StringBuilder,
  Chilkat.Rest,
  Chilkat.AuthAws,
  Chilkat.JsonObject,
  Chilkat.Socket;

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

procedure RunDemo;
var
  success: Boolean;
  createTemplate: Boolean;
  region: string;
  host: TStringBuilder;
  signer: TAuthAws;
  connection: TSocket;
  rest: TRest;
  sessionToken: string;
  request: TJsonObject;
  setupResponse: string;
  order: TJsonObject;
  tryMissingField: Boolean;
  preview: TJsonObject;
  responseText: string;
  response: TJsonObject;

begin
  success := False;

  //  Assumes Chilkat is unlocked. See Global Unlock Sample.
  success := False;

  createTemplate := True;
  //  Use the same AWS Region for the identity, endpoint, and Signature Version 4.
  region := 'us-west-2';
  host := TStringBuilder.Create;
  host.Append('email.');
  host.Append(region);
  host.Append('.amazonaws.com');

  signer := TAuthAws.Create;
  //  Supply the credentials from your application's credential provider.
  signer.AccessKey := 'AWS_ACCESS_KEY_ID';
  signer.SecretKey := 'AWS_SECRET_ACCESS_KEY';
  signer.Region := region;
  signer.ServiceName := 'ses';

  connection := TSocket.Create;
  connection.RequireSslCertVerify := True;
  success := connection.Connect(host.GetAsString(),443,True,10000);
  if (success <> True) then
    begin
      WriteLn(connection.LastErrorText);
      Exit;
    end;

  rest := TRest.Create;
  success := rest.UseConnection(connection,False);
  if (success <> True) then
    begin
      WriteLn(rest.LastErrorText);
      Exit;
    end;
  success := rest.SetAuthAws(signer);
  if (success <> True) then
    begin
      WriteLn(rest.LastErrorText);
      Exit;
    end;
  //  For temporary AWS credentials, supply the session token from the same provider.
  sessionToken := '';
  if (sessionToken <> '') then
    begin
      rest.AddQueryParam('X-Amz-Security-Token',sessionToken);
    end;
  if (createTemplate = True) then
    begin
      request := TJsonObject.Create;
      request.UpdateString('TemplateName','OrderReceipt');
      request.UpdateString('TemplateContent.Subject','Receipt for {{orderNumber}}');
      request.UpdateString('TemplateContent.Text','Thank you, {{firstName}}. Order {{orderNumber}}: {{#each items}}{{quantity}} x {{name}}. {{/each}}');
      request.UpdateString('TemplateContent.Html','<p>Thank you, {{firstName}}.</p><ul>{{#each items}}<li>{{quantity}} x {{name}}</li>{{/each}}</ul>');

      rest.AddHeader('Content-Type','application/json');
      setupResponse := rest.FullRequestString('POST','/v2/email/templates',request.Emit());
      if (rest.LastMethodSuccess <> True) then
        begin
          WriteLn(rest.LastErrorText);
          Exit;
        end;
      if (rest.ResponseStatusCode <> 200) then
        begin
          WriteLn('SES returned HTTP ' + rest.ResponseStatusCode + ' ' + setupResponse);
          Exit;
        end;
      WriteLn('Template created. Set createTemplate to false to preview it.');
      Exit;
    end;
  order := TJsonObject.Create;
  order.UpdateString('firstName','Avery');
  order.UpdateString('orderNumber','1042');
  order.UpdateString('items[0].name','Notebook');
  order.UpdateInt('items[0].quantity',2);
  order.UpdateString('items[1].name','Pen');
  order.UpdateInt('items[1].quantity',1);
  //  Remove this key to try the missing-field case.
  tryMissingField := False;
  if (tryMissingField = True) then
    begin
      order.Delete('orderNumber');
    end;
  preview := TJsonObject.Create;
  preview.UpdateString('TemplateData',order.Emit());

  rest.AddHeader('Content-Type','application/json');
  responseText := rest.FullRequestString('POST','/v2/email/templates/OrderReceipt/render',preview.Emit());
  if (rest.LastMethodSuccess <> True) then
    begin
      WriteLn(rest.LastErrorText);
      Exit;
    end;
  if (rest.ResponseStatusCode <> 200) then
    begin
      WriteLn('SES returned HTTP ' + rest.ResponseStatusCode + ' ' + responseText);
      Exit;
    end;
  response := TJsonObject.Create;
  success := response.Load(responseText);
  if (success <> True) then
    begin
      WriteLn(response.LastErrorText);
      Exit;
    end;
  WriteLn(response.StringOf('RenderedTemplate'));


  host.Free;
  signer.Free;
  connection.Free;
  rest.Free;
      request.Free;
  order.Free;
  preview.Free;
  response.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.