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

Reply to a message in its existing Gmail thread

See more GMail REST API Examples

Live send. Supply the Gmail ID of a received message and use an authorized From address. Fetch its raw MIME so Chilkat.Email can parse encoded headers and recipient addresses. Send a plain-text reply to Reply-To, falling back to From. The reply goes to the original sender or reply address.

The request supplies Gmail’s threadId and matching Subject. The MIME In-Reply-To contains the original RFC Message-ID. References preserves the conversation ancestry and appends that Message-ID. Select a message with a valid Message-ID and review its recipient before running this sending example. Authorize both gmail.readonly and gmail.send, or use gmail.modify as shown below.

Authorize the application with https://www.googleapis.com/auth/gmail.modify. The example reads the access token from gmail-token.json in a private working directory. Authorize a desktop application.

Google documentation

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.HttpResponse,
  Chilkat.Email,
  Chilkat.StringBuilder,
  Chilkat.JsonObject,
  Chilkat.Http,
  Chilkat.BinData;

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

procedure RunDemo;
var
  success: Boolean;
  token: TJsonObject;
  http: THttp;
  resp: THttpResponse;
  reply: TJsonObject;
  url: TStringBuilder;
  threadId: string;
  originalMime: TBinData;
  original: TEmail;
  messageIdHeader: string;
  email: TEmail;
  replyAddress: string;
  references: TStringBuilder;
  previousReferences: string;
  mime: TBinData;
  request: TJsonObject;

begin
  success := False;

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

  token := TJsonObject.Create;
  success := token.LoadFile('gmail-token.json');
  if (success <> True) then
    begin
      WriteLn('Could not read gmail-token.json from the private working directory.');
      Exit;
    end;
  if ((token.JsonTypeOf('access_token') <> 1) or (token.StringOfEquals('access_token','',True) = True)) then
    begin
      WriteLn('An OAuth access token is required.');
      Exit;
    end;
  http := THttp.Create;
  http.RequireSslCertVerify := True;
  http.AuthToken := token.StringOf('access_token');
  resp := THttpResponse.Create;
  reply := TJsonObject.Create;
  url := TStringBuilder.Create;
  url.Append('https://gmail.googleapis.com/gmail/v1/users/me/messages/');
  url.Append('GMAIL_MESSAGE_ID');
  url.Append('?format=raw');
  success := http.HttpNoBody('GET',url.GetAsString(),resp);
  if (resp.StatusCode = 0) then
    begin
      WriteLn('Gmail did not return an HTTP response.');
      Exit;
    end;
  if ((success <> True) or (resp.StatusCode < 200) or (resp.StatusCode >= 300)) then
    begin
      WriteLn('Gmail HTTP ' + resp.StatusCode);
      success := reply.Load(resp.BodyStr);
      if (success = True) then
        begin
          WriteLn(reply.StringOf('error.message'));
        end;
      Exit;
    end;
  success := reply.Load(resp.BodyStr);
  if (success <> True) then
    begin
      WriteLn('Expected a Gmail JSON response.');
      Exit;
    end;
  if ((reply.JsonTypeOf('threadId') <> 1) or (reply.StringOfEquals('threadId','',True) = True)) then
    begin
      WriteLn('Expected threadId in the response.');
      Exit;
    end;
  if ((reply.JsonTypeOf('raw') <> 1) or (reply.StringOfEquals('raw','',True) = True)) then
    begin
      WriteLn('Expected raw in the response.');
      Exit;
    end;
  threadId := reply.StringOf('threadId');
  originalMime := TBinData.Create;
  success := reply.BytesOf('raw','base64url',originalMime);
  if (success <> True) then
    begin
      WriteLn(reply.LastErrorText);
      Exit;
    end;
  original := TEmail.Create;
  success := original.SetFromMimeBd(originalMime);
  if (success <> True) then
    begin
      WriteLn(original.LastErrorText);
      Exit;
    end;
  messageIdHeader := original.GetHeaderField('Message-ID');
  if ((original.LastMethodSuccess <> True) or (messageIdHeader = '')) then
    begin
      WriteLn('The original message needs a Message-ID for this threaded reply.');
      Exit;
    end;
  email := TEmail.Create;
  email.From := 'Sender <sender@example.com>';
  //  Use the parsed Reply-To mailbox list when present, otherwise use From.
  replyAddress := original.ReplyTo;
  if (replyAddress = '') then
    begin
      replyAddress := original.From;
    end;
  success := email.AddMultipleTo(replyAddress);
  if (success <> True) then
    begin
      WriteLn(email.LastErrorText);
      Exit;
    end;
  if (email.NumTo = 0) then
    begin
      WriteLn('The original message has no usable reply address.');
      Exit;
    end;
  email.Subject := original.Subject;
  email.Charset := 'utf-8';
  email.Body := 'Thank you for your message.';
  email.AddHeaderField('In-Reply-To',messageIdHeader);
  references := TStringBuilder.Create;
  previousReferences := original.GetHeaderField('References');
  if ((original.LastMethodSuccess = True) and (previousReferences <> '')) then
    begin
      references.Append(previousReferences);
      references.Append(' ');
    end;
  references.Append(messageIdHeader);
  email.AddHeaderField('References',references.GetAsString());
  mime := TBinData.Create;
  success := email.GetMimeBd(mime);
  if (success <> True) then
    begin
      WriteLn(email.LastErrorText);
      Exit;
    end;
  request := TJsonObject.Create;
  success := request.UpdateBd('raw','base64url',mime);
  if (success <> True) then
    begin
      WriteLn(request.LastErrorText);
      Exit;
    end;
  success := request.UpdateString('threadId',threadId);
  if (success <> True) then
    begin
      WriteLn(request.LastErrorText);
      Exit;
    end;
  success := http.HttpJson('POST','https://gmail.googleapis.com/gmail/v1/users/me/messages/send',request,'application/json',resp);
  if (resp.StatusCode = 0) then
    begin
      WriteLn('Gmail did not return an HTTP response.');
      Exit;
    end;
  if ((success <> True) or (resp.StatusCode < 200) or (resp.StatusCode >= 300)) then
    begin
      WriteLn('Gmail HTTP ' + resp.StatusCode);
      success := reply.Load(resp.BodyStr);
      if (success = True) then
        begin
          WriteLn(reply.StringOf('error.message'));
        end;
      Exit;
    end;
  success := reply.Load(resp.BodyStr);
  if (success <> True) then
    begin
      WriteLn('Expected a Gmail JSON response.');
      Exit;
    end;
  if ((reply.JsonTypeOf('id') <> 1) or (reply.StringOfEquals('id','',True) = True)) then
    begin
      WriteLn('Expected id in the response.');
      Exit;
    end;
  WriteLn('Sent reply ID: ' + reply.StringOf('id'));
  WriteLn('Thread ID: ' + reply.StringOf('threadId'));


  token.Free;
  http.Free;
  resp.Free;
  reply.Free;
  url.Free;
  originalMime.Free;
  original.Free;
  email.Free;
  references.Free;
  mime.Free;
  request.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.