STARTTLS error while sending email using Indy in Delphi XE

ae1080 picture ae1080 · Oct 10, 2011 · Viewed 16.4k times · Source

I'm trying to send email from my application using the following code:

  Var
  MailMessage : TIdMessage;
  SMTP        : TIdSMTP
   .
   .
   .
 //setup SMTP
 SMTP.Host := 'smtp.gmail.com';
 SMTP.Port := 25;
 //setup mail message
 MailMessage.From.Address := '[email protected]';
 MailMessage.Recipients.EMailAddresses := '[email protected]';
 MailMessage.Subject := 'Test';
 MailMessage.Body.Text := 'Hello, It is Just for test';

 SMTP.Connect;
 SMTP.Send(MailMessage);

When i run it, it generates the following error

**ERROR: Must issue a STARTTLS command first. i29sm34080394wbp.22**

How can I solve this?

Answer

TLama picture TLama · Oct 10, 2011

By putting the answers together you can get the following code. Don't forget as Nathanial Woolls mentioned here to put the libeay32.dll and ssleay32.dll libraries for instance from here to your project folder or to a path from the following places.

uses
  IdMessage, IdSMTP, IdSSLOpenSSL, IdGlobal, IdExplicitTLSClientServerBase;

procedure SendEmail(const Recipients: string; const Subject: string; const Body: string);
var
  SMTP: TIdSMTP;
  Email: TIdMessage;
  SSLHandler: TIdSSLIOHandlerSocketOpenSSL;
begin
  SMTP := TIdSMTP.Create(nil);
  Email := TIdMessage.Create(nil);
  SSLHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);

  try
    SSLHandler.MaxLineAction := maException;
    SSLHandler.SSLOptions.Method := sslvTLSv1;
    SSLHandler.SSLOptions.Mode := sslmUnassigned;
    SSLHandler.SSLOptions.VerifyMode := [];
    SSLHandler.SSLOptions.VerifyDepth := 0;

    SMTP.IOHandler := SSLHandler;
    SMTP.Host := 'smtp.gmail.com';
    SMTP.Port := 587;
    SMTP.Username := '[email protected]';
    SMTP.Password := 'yourpassword';
    SMTP.UseTLS := utUseExplicitTLS;

    Email.From.Address := '[email protected]';
    Email.Recipients.EmailAddresses := Recipients;
    Email.Subject := Subject;
    Email.Body.Text := Body;

    SMTP.Connect;
    SMTP.Send(Email);
    SMTP.Disconnect;

  finally
    SMTP.Free;
    Email.Free;
    SSLHandler.Free;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  SendEmail('[email protected]', 'Subject', 'Body');
end;

Hope this help