Sample code for 30+ languages & platforms
Lazarus Pascal

Amazon SES v2: Send a raw MIME email with a PDF attachment

See more Amazon SES Examples

Place invoice.pdf in the working directory. Chilkat builds the MIME message and gives the attachment the name invoice-1042.pdf. The v2 SendEmail request carries those bytes in Content.Raw.Data. For a blind copy, supply the address in Destination.BccAddresses and keep it out of the MIME headers.

Use a verified sender and grant ses:SendEmail for this v2 operation. The v2 message size limit is 40 MB including attachments after MIME encoding. For a straightforward attachment that needs no custom MIME layout, v2 also supports Content.Simple.Attachments.

Sending raw email · SES attachments · Sending quotas

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

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

procedure RunDemo;
var
  success: Boolean;
  pdf: TBinData;
  sender: string;
  recipient: string;
  email: TEmail;
  mime: TBinData;
  request: TJsonObject;
  region: string;
  host: TStringBuilder;
  signer: TAuthAws;
  connection: TSocket;
  rest: TRest;
  sessionToken: string;
  responseText: string;
  result: TJsonObject;

begin
  success := False;

  //  Assumes Chilkat is unlocked. See Global Unlock Sample.

  success := False;

  //  Read the PDF before making a network request.
  pdf := TBinData.Create;
  success := pdf.LoadFile('invoice.pdf');
  if (success <> True) then
    begin
      WriteLn(pdf.LastErrorText);
      Exit;
    end;
  if (pdf.NumBytes = 0) then
    begin
      WriteLn('invoice.pdf is empty.');
      Exit;
    end;
  sender := 'sender+reports@example.com';
  recipient := 'success@simulator.amazonses.com';
  email := TEmail.Create;
  email.From := sender;
  email.Subject := 'Invoice 1042';
  email.Charset := 'utf-8';
  success := email.AddTo('',recipient);
  if (success <> True) then
    begin
      WriteLn(email.LastErrorText);
      Exit;
    end;
  email.AddPlainTextAlternativeBody('Invoice 1042 is attached.');
  email.AddHtmlAlternativeBody('<p>Invoice <strong>1042</strong> is attached.</p>');
  success := email.AddAttachmentBd('invoice-1042.pdf',pdf,'application/pdf');
  if (success <> True) then
    begin
      WriteLn(email.LastErrorText);
      Exit;
    end;
  //  Get the exact MIME bytes, including the attachment's transfer encoding.
  mime := TBinData.Create;
  success := email.GetMimeBd(mime);
  if (success <> True) then
    begin
      WriteLn(email.LastErrorText);
      Exit;
    end;
  //  Base64 here transports the entire MIME message as a blob in the JSON request.
  request := TJsonObject.Create;
  request.UpdateString('FromEmailAddress',sender);
  request.UpdateString('Destination.ToAddresses[0]',recipient);
  request.UpdateString('Content.Raw.Data',mime.GetEncoded('base64'));

  //  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;

  rest.AddHeader('Content-Type','application/json');
  responseText := rest.FullRequestString('POST','/v2/email/outbound-emails',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 + ' ' + responseText);
      Exit;
    end;
  result := TJsonObject.Create;
  success := result.Load(responseText);
  if (success <> True) then
    begin
      WriteLn(result.LastErrorText);
      Exit;
    end;
  if (result.HasMember('MessageId') <> True) then
    begin
      WriteLn('SES returned no message ID.');
      Exit;
    end;
  WriteLn('SES accepted the message. Message ID: ' + result.StringOf('MessageId'));


  pdf.Free;
  email.Free;
  mime.Free;
  request.Free;
  host.Free;
  signer.Free;
  connection.Free;
  rest.Free;
  result.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.