How to fix - Must issue a STARTTLS command first

979 Views Asked by At

Note - I am not extremely experienced in Delphi coding, and have minimal knowledge of this subject I am attempting to fix.

My problem is that I am attempting to send an email to a user containing "Shipment Details", this is based off of my programs needs.

My code giving me an error looks like this:

procedure TForm1.FormCreate(Sender: TObject);
var
  smtp: TIdSMTP;
  msg: TIdMessage;
  sslHandler: TIdSSLIOHandlerSocketOpenSSL;
begin
  try
    smtp := TIdSMTP.Create(nil);
    msg := TIdMessage.Create(nil);
    sslHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
    try
      // Configure SSL handler
      sslHandler.SSLOptions.Method := sslvTLSv1_2;
      sslHandler.SSLOptions.Mode := sslmUnassigned;
      // Configure SMTP settings
      smtp.IOHandler := sslHandler;
      smtp.Host := 'smtp.gmail.com';
      smtp.Port := 587;
      smtp.Username := '';
      smtp.Password := '';

      // Create email message
      msg.From.Address := '';
      msg.Recipients.Add.Address := '';
      msg.Subject := 'Delphi Test Email';

      with TIdText.Create(msg.MessageParts, nil) do
      begin
        Body.Text := 'This is a test';
      end;
      // Connect and send email
      smtp.Connect;
      try
        smtp.Send(msg);
      finally
        smtp.Disconnect;
      end;
    finally
      // Clean up
      sslHandler.Free;
      msg.Free;
      smtp.Free;
    end;
  except
    on E: Exception do
      ShowMessage('An error occurred: ' + E.Message);
  end;
end;

I have the relevant components on my form and my uses clause looks like this:

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IdComponent, IdTCPConnection,
  IdTCPClient, IdExplicitTLSClientServerBase, IdMessageClient, IdSMTPBase,
  IdBaseComponent, IdSMTP, IdMessage, IdText, IdSSLOpenSSL, IdIOHandler,
  IdIOHandlerSocket, IdIOHandlerStack, IdSSL;

I have no idea how to fix this error.

Note: I have obviously entered all empty string values needed and have tried to set up a custom App password, but to no avail. The error still appears.

1

There are 1 best solutions below

0
Remy Lebeau On

To use the STARTTLS command, you need to set the TIdSMTP.UseTLS property to utUseExplicitTLS after assigning the TIdSMTP.IOHandler property and before calling the TIdSMTP.Connect() method.

...
smtp.IOHandler := sslHandler;
smtp.Host := 'smtp.gmail.com';
smtp.Port := 587;
...
smtp.UseTLS := utUseExplicitTLS; // <-- ADD THIS!
...
smtp.Connect;
...