Sample code for 30+ languages & platforms
Lazarus Pascal Requires Chilkat v11.0.0+

Constant Contact V3: LIVE SEND - Schedule a newsletter for a named list

See more Constant Contact Examples

LIVE SEND. Scheduling this campaign delivers email to eligible contacts on the selected list at the specified time. Use the reviewer test to check the email first. Select the intended newsletter and list in the same account. The example accepts a primary draft, replaces its entire audience with one active email list, and schedules it. List lookup requires contact_data. Editing and scheduling require campaign_data and account privileges to edit and send.

Enter a future ISO 8601 timestamp with a UTC offset or Z. To cancel before delivery starts, keep the same activity selection, change action to unschedule, and run again. Cancellation removes the schedule and keeps the audience assignment. If the scheduling response is lost, check the activity’s schedule before retrying.

Authorize the application using the same account and credential store.

Constant Contact developer guide

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.CkDateTime,
  Chilkat.HttpResponse,
  Chilkat.HttpRequest,
  Chilkat.JsonObject,
  Chilkat.Secrets,
  Chilkat.Http;

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

procedure RunDemo;
var
  success: Boolean;
  vault: TSecrets;
  entry: TJsonObject;
  tokens: TJsonObject;
  loaded: Boolean;
  http: THttp;
  resp: THttpResponse;
  selection: TJsonObject;
  activityId: string;
  action: string;
  deliveryTime: string;
  delivery: TCkDateTime;
  now: TCkDateTime;
  listName: string;
  query: THttpRequest;
  matches: TJsonObject;
  listId: string;
  draft: TJsonObject;
  updated: TJsonObject;
  schedule: TJsonObject;

begin
  success := False;

  //  LIVE SEND: Scheduling this activity delivers email to the selected contact list.
  //  Assumes Chilkat is unlocked. See Global Unlock Sample.
  vault := TSecrets.Create;
  vault.Location := 'local_manager';
  vault.AutoSplit := True;
  entry := TJsonObject.Create;
  entry.UpdateString('appName','ConstantContactV3');
  entry.UpdateString('service','OAuth2');
  entry.UpdateString('username','my-account');
  tokens := TJsonObject.Create;
  loaded := vault.GetSecretJson(entry,tokens);
  if (loaded <> True) then
    begin
      WriteLn('Run the desktop authorization example using this account and store.');
      Exit;
    end;
  if (tokens.JsonTypeOf('access_token') <> 1) then
    begin
      WriteLn('The saved authorization has no access token.');
      Exit;
    end;
  http := THttp.Create;
  http.RequireSslCertVerify := True;
  http.AuthToken := tokens.StringOf('access_token');
  resp := THttpResponse.Create;

  //  Use the selection file from the draft or campaign lookup example for this account.
  selection := TJsonObject.Create;
  success := selection.LoadFile('newsletter-selection.json');
  activityId := selection.StringOf('campaign_activity_id');
  if ((success <> True) or (activityId = '')) then
    begin
      WriteLn('Select a campaign and save its primary activity ID first.');
      Exit;
    end;
  http.SetUrlVar('activity',activityId);
  action := 'schedule';
  if (action = 'unschedule') then
    begin
      success := http.HttpNoBody('DELETE','https://api.cc.email/v3/emails/activities/{$activity}/schedules',resp);
      if ((success <> True) and (resp.StatusCode <= 0)) then
        begin
          WriteLn('Remove schedule: HTTP request failed.');
          Exit;
        end;
      if ((success <> True) or (resp.StatusCode <> 204)) then
        begin
          WriteLn('Remove schedule: HTTP ' + resp.StatusCode + ' ' + resp.BodyStr);
          Exit;
        end;
      WriteLn('Schedule removed for activity ' + activityId);
      Exit;
    end;
  if (action <> 'schedule') then
    begin
      WriteLn('Choose schedule or unschedule.');
      Exit;
    end;
  //  Replace the placeholder with the intended future delivery time, e.g. 2030-05-15T09:00:00-05:00.
  deliveryTime := 'ENTER_FUTURE_TIMESTAMP_WITH_OFFSET';
  delivery := TCkDateTime.Create;
  now := TCkDateTime.Create;
  now.SetFromCurrentSystemTime();
  success := delivery.SetFromTimestamp(deliveryTime);
  if ((success <> True) or (delivery.DiffSeconds(now) <= 0)) then
    begin
      WriteLn('Enter a valid future delivery time with a UTC offset or Z.');
      Exit;
    end;
  //  Use the full display name. AddParam encodes spaces and punctuation.
  listName := 'Workshop announcements';
  query := THttpRequest.Create;
  query.HttpVerb := 'GET';
  query.AddParam('name',listName);
  query.AddParam('status','active');
  query.AddParam('include_membership_count','active');
  success := http.HttpReq('https://api.cc.email/v3/contact_lists',query,resp);
  if ((success <> True) and (resp.StatusCode <= 0)) then
    begin
      WriteLn('Look up list: HTTP request failed.');
      Exit;
    end;
  if ((success <> True) or (resp.StatusCode <> 200)) then
    begin
      WriteLn('Look up list: HTTP ' + resp.StatusCode + ' ' + resp.BodyStr);
      Exit;
    end;
  matches := TJsonObject.Create;
  success := matches.Load(resp.BodyStr);
  if (success <> True) then
    begin
      WriteLn('Expected a JSON object in the response.');
      Exit;
    end;
  if (matches.SizeOfArray('lists') = 0) then
    begin
      WriteLn('No active email list named ' + listName);
      Exit;
    end;
  if ((matches.SizeOfArray('lists') <> 1) or (matches.StringOfEquals('lists[0].name',listName,True) <> True)) then
    begin
      WriteLn('Expected one exact list name.');
      Exit;
    end;
  listId := matches.StringOf('lists[0].list_id');
  if (listId = '') then
    begin
      WriteLn('Missing list ID.');
      Exit;
    end;
  WriteLn(listName + ' | List ID: ' + listId + ' | Mailable contacts: ' + matches.IntOf('lists[0].membership_count'));

  //  PUT replaces the activity. Read it first to preserve the subject, sender and other settings.
  //  Constant Contact retains omitted subresources such as html_content and the physical footer.
  success := http.HttpNoBody('GET','https://api.cc.email/v3/emails/activities/{$activity}',resp);
  if ((success <> True) and (resp.StatusCode <= 0)) then
    begin
      WriteLn('Read draft: HTTP request failed.');
      Exit;
    end;
  if ((success <> True) or (resp.StatusCode <> 200)) then
    begin
      WriteLn('Read draft: HTTP ' + resp.StatusCode + ' ' + resp.BodyStr);
      Exit;
    end;
  draft := TJsonObject.Create;
  success := draft.Load(resp.BodyStr);
  if (success <> True) then
    begin
      WriteLn('Expected a JSON object in the response.');
      Exit;
    end;
  if ((draft.StringOfEquals('role','primary_email',True) <> True) or (draft.StringOfEquals('current_status','DRAFT',True) <> True)) then
    begin
      WriteLn('Select a primary activity in DRAFT status.');
      Exit;
    end;
  WriteLn('LIVE SEND: ' + draft.StringOf('subject') + ' | Activity: ' + activityId + ' | List: ' + listName + ' | Delivery: ' + deliveryTime);
  draft.UpdateNewArray('contact_list_ids');
  draft.UpdateString('contact_list_ids[0]',listId);
  draft.UpdateNewArray('segment_ids');
  success := http.HttpJson('PUT','https://api.cc.email/v3/emails/activities/{$activity}',draft,'application/json',resp);
  if ((success <> True) and (resp.StatusCode <= 0)) then
    begin
      WriteLn('Assign audience: HTTP request failed.');
      Exit;
    end;
  if ((success <> True) or (resp.StatusCode <> 200)) then
    begin
      WriteLn('Assign audience: HTTP ' + resp.StatusCode + ' ' + resp.BodyStr);
      Exit;
    end;
  updated := TJsonObject.Create;
  success := updated.Load(resp.BodyStr);
  if (success <> True) then
    begin
      WriteLn('Expected a JSON object in the response.');
      Exit;
    end;
  if ((updated.SizeOfArray('contact_list_ids') <> 1) or (updated.StringOfEquals('contact_list_ids[0]',listId,True) <> True) or (updated.SizeOfArray('segment_ids') > 0)) then
    begin
      WriteLn('The saved audience did not match the requested list. Scheduling stopped.');
      Exit;
    end;
  schedule := TJsonObject.Create;
  schedule.UpdateString('scheduled_date',delivery.GetAsTimestamp(False));
  success := http.HttpJson('POST','https://api.cc.email/v3/emails/activities/{$activity}/schedules',schedule,'application/json',resp);
  if ((success <> True) or (resp.StatusCode < 200) or (resp.StatusCode >= 300)) then
    begin
      WriteLn('Schedule not confirmed. HTTP ' + resp.StatusCode);
      WriteLn('The audience was saved. Check the schedule before retrying.');
      Exit;
    end;
  WriteLn('Live delivery scheduled for ' + schedule.StringOf('scheduled_date') + ' to ' + listName);


  vault.Free;
  entry.Free;
  tokens.Free;
  http.Free;
  resp.Free;
  selection.Free;
  delivery.Free;
  now.Free;
  query.Free;
  matches.Free;
  draft.Free;
  updated.Free;
  schedule.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.