Aunque el IDE de programación Borland Delphi 6 está obsoleto y tiene más de 10 años, sigue habiendo una comunidad de desarrolladores que lo usan, bien por su versatilidad y eficiencia, capaz de generar aplicaciones que siguen funcionando en entornos Windows 10 y Server 2012, bien porque tienen aplicaciones relativamente grandes que no se migraron a otros entornos. En este caso explicamos cómo poder realizar envíos de correos electrónicos (incluso con adjuntos) usando el protocolo TLS / SSL. Realizaremos la explicación para Borland Delphi 6 y usaremos los componentes gratuitos open source Indy 10. Esto nos permitirá enviar correos electrónicos desde nuestras aplicaciones Delphi usando el protocolo seguro TLS, sucesor del SSL.

Requisitos para enviar correos electrónicos emails usando SSL TLS con Delphi e Indy

Necesitaremos disponer del IDE de desarrollo Borland Delphi 6 (o alguna versión superior). Como componente usaremos Indy Internet Direct en su versión 10. Con Delphi 6 se puede instalar la versión 9 pero esta no es compatible con TLS SSL para el envío de emails, por lo que tendremos que desinstalar la anterior e instalar la nueva versión (lo explicaremos más adelante).

Parte de este artículo es válido para otras versiones de Delphi e incluso otros IDE de desarrollo que puedan usar Indy: Kylix, Lazarus, Delphi for .NET, etc..

Desinstalar Indy 9 (o cualquier versión anterior) en Delphi y equipo Windows

Antes de proceder realizaremos una copia de seguridad del equipo, si es una máquina virtual realizaremos un snapshot o bien una copia completa de la máquina. De forma que si tenemos cualquier problema en la instalación o desinstalación de Indy podremos volver al estado anterior.

En nuestro caso realizaremos el proceso en un equipo con Windows XP, aunque es similar si usamos otra versión del sistema operativo Windows.

Cerraremos Delphi si lo tenemos abierto y accederemos a Agregar o quitar programas en el Panel de Control de Windows. Buscaremos Borland Delphi 6 (o la versión que tengamos instalada) y pulsaremos en «Cambiar»:

Desinstalar Indy 9 (o cualquier versión anterior) en Delphi y equipo Windows

Se iniciará el asistente de instalación de Delphi, puede que nos solicite la ubicación del CD de instalación de Delphi:

Desinstalar Indy 9 (o cualquier versión anterior) en Delphi y equipo Windows

En este caso pulsaríamos «Browse» y buscaríamos el CD o lugar donde tengamos los ficheros de instalación de Delphi, en concreto buscaremos «Borland Delphi 6.msi» que está en la carpeta «Install» del CD:

Desinstalar Indy 9 (o cualquier versión anterior) en Delphi y equipo Windows

Pulsaremos «Next» en el asistente de instalación de Borland Delphi:

Desinstalar Indy 9 (o cualquier versión anterior) en Delphi y equipo Windows

Marcaremos «Modify» y pulsaremos «Next»:

Desinstalar Indy 9 (o cualquier versión anterior) en Delphi y equipo Windows

En el grupo «Program Files» buscaremos «Indy» y pulsaremos sobre el desplegable, elegiremos «Dot Not Install»:

Desinstalar Indy 9 (o cualquier versión anterior) en Delphi y equipo Windows

Pulsaremos «Next» y seguiremos el proceso de instalación habitual, en nuestro caso no instalaremos «VisiBroker» por lo que marcaremos «No VisiBroker/CORBA Support»:

Desinstalar Indy 9 (o cualquier versión anterior) en Delphi y equipo Windows

Pulsaremos «Install»:

Desinstalar Indy 9 (o cualquier versión anterior) en Delphi y equipo Windows

Una vez desinstaladas las Indy abriremos Delphi, puede que al iniciar por primera vez nos muestre este error:

Desinstalar Indy 9 (o cualquier versión anterior) en Delphi y equipo Windows

Con el texto: Can’t load package C:Archivos de programaBorlandDelphi6Bindclindy60.bpl. No se puede encontrar el módulo especificado. Do you want to attempt to load this package the next time a project is loaded?

Indicando que no se puede cargar el paquete Indy porque, obviamente, lo hemos desinstalado y si queremos volver a intentarlo la próxima vez. Responderemos pulsando «No».

Nos aseguraremos de que no ha quedado rastro de las Indy, desde el menú «Component» – «Install Packages»:

Desinstalar Indy 9 (o cualquier versión anterior) en Delphi y equipo Windows

Buscaremos «Internet Direct (Indy) for D6 Property and Component Editors», lo seleccionaremos y pulsaremos en «Remove»:

Desinstalar Indy 9 (o cualquier versión anterior) en Delphi y equipo Windows

Y pulsaremos «Yes» en la confirmación de eliminación del paquete dclindy60.bpl:

Desinstalar Indy 9 (o cualquier versión anterior) en Delphi y equipo Windows

Accederemos al menú «Component» – «Configure Palette»:

Desinstalar Indy 9 (o cualquier versión anterior) en Delphi y equipo Windows

Y buscaremos también cualquier rastro de Indy para eliminarlo: Indy Clients, Indy Servers, Indy Misc:

Desinstalar Indy 9 (o cualquier versión anterior) en Delphi y equipo Windows

Cerraremos Delphi y lo volveremos a abrir, asegurándonos de que ya no aparecen pestañas de Indy por el IDE de Delphi ni mensajes de error.

Descargar e instalar Indy 10 en Borland Delphi 6

Podemos descargar Indy de su web oficial, en su versión 10.0.52, desde este enlace: http://www.indyproject.org/downloads/10/indy10.0.52_source.zip, o bien desde nuestra propio sitio web, donde dejamos esta versión por si la web oficial cierra, ya que lleva varios años sin realizar actualizaciones. Para la descarga desde nuestro sitio web:

Una vez descargado el fichero zip lo descomprimiremos, debe tener las siguientes carpetas:

  • Core
  • Protocols
  • SuperCache
  • System

Usaremos todas las carpetas salvo SuperCache. Copiaremos las carpetas Core, Protocols y System a la carpeta lib de delphi, que normalmente está ubicada en:

C:Archivos de programaBorlandDelphi6Lib

Descargar e instalar Indy 10 en Borland Delphi 6
Descargar e instalar Indy 10 en Borland Delphi 6

Abriremos Delphi y pulsaremos en el menú «File» – «Open»:

Descargar e instalar Indy 10 en Borland Delphi 6

Siguiendo el siguiente orden iremos compilando los ficheros dpk de Indy, escogiendo el fichero de la versión para Delphi, en nuestro caso todas las que acaben en 60. Empezaremos por IndySystem60.dpk ubicado en la carpeta System (de las que hemos copiado anteriormente):

Descargar e instalar Indy 10 en Borland Delphi 6

Pulsaremos en «Compile»:

Descargar e instalar Indy 10 en Borland Delphi 6

Normalmente no debe mostrar mensajes. Sin cerrar volveremos al menú «File» – «Open» y elegiremos esta vez el fichero IndyCore60.dpk ubicado en Core:

Descargar e instalar Indy 10 en Borland Delphi 6

Lo compilaremos con «Compile» y repetiremos el mismo proceso (abrir y compilar), por orden, para IndyProtocols60.dpk ubicado en Protocols, dclIndyCore60.dpk  ubicado en Core y dclIndyProtocols60.dpk ubicado en Protocols.

Para el caso de IndyProtocols60.dpk, mostrará este warning, que es normal:

[Warning] IdGlobalProtocols.pas(1445): Return value of function ‘GetGMTDateByName’ might be undefined

Desde el menú de Delphi «Tools» – «Environment Options»:

Descargar e instalar Indy 10 en Borland Delphi 6

Pulsaremos en la pestaña «Library» y en la primera línea «Library path» pulsaremos en el botón de los tres puntos para ir agregando las carpetas anteriores (Core, System, Protocols):

Descargar e instalar Indy 10 en Borland Delphi 6

Seleccionaremos «Core»:

Descargar e instalar Indy 10 en Borland Delphi 6

Y pulsaremos «Add»:

Descargar e instalar Indy 10 en Borland Delphi 6

Repetiremos el proceso con System y Protocols, quedando:

Descargar e instalar Indy 10 en Borland Delphi 6

Por último, de las ventanas que tenemos abiertas de las compilaciones, buscaremos la de Package – dclIndyCore60.dpk y pulsaremos «Install»:

Descargar e instalar Indy 10 en Borland Delphi 6

Si todo es correcto nos mostrará un mensaje como el siguiente:

Descargar e instalar Indy 10 en Borland Delphi 6

Con el texto: Package c:archivos de programaborlanddelphi6ProjectsBpldclIndyCore60.bpl has been installed.
The following new component(s) have been registered: IdAntiFreeze.TIdAntiFreeze, IdCmdTCPClient.TIdCmdTCPClient, IdCmdTCPServer.TIdCmdTCPServer, IdIcmpClient.TIdIcmpClient, IdIntercept.TIdConnectionIntercept, IdInterceptSimLog.TIdInterceptSimLog, IdInterceptThrottler.TIdInterceptThrottler, IdIOHandlerStack.TIdIOHandlerStack, IdIOHandlerStream.TIdIOHandlerStream, IdLogDebug.TIdLogDebug, IdLogEvent.TIdLogEvent, IdLogFile.TIdLogFile, IdLogStream.TIdLogStream, IdSchedulerOfThreadDefault.TIdSchedulerOfThreadDefault, IdSchedulerOfThreadPool.TIdSchedulerOfThreadPool, IdServerIOHandlerStack.TIdServerIOHandlerStack, IdSimpleServer.TIdSimpleServer, IdSocks.TIdSocksInfo, IdTCPClient.TIdTCPClient, IdTCPServer.TIdTCPServer, IdThreadComponent.TIdThreadComponent, IdUDPClient.TIdUDPClient, IdUDPServer.TIdUDPServer.

Repetiremos el proceso para la ventana Package – dclIndyProtocols60.dpk, pulsando en «Install»:

Descargar e instalar Indy 10 en Borland Delphi 6

que si todo es correcto nos mostrará este otro mensaje:

Descargar e instalar Indy 10 en Borland Delphi 6

Con el texto: Package c:archivos de programaborlanddelphi6ProjectsBpldclIndyProtocols60.bpl has been installed.
The following new component(s) have been registered: IdChargenServer.TIdChargenServer, IdChargenUDPServer.TIdChargenUDPServer, IdCoderMIME.TIdDecoderMIME, IdCoderMIME.TIdEncoderMIME, IdCoderQuotedPrintable.TIdDecoderQuotedPrintable, IdCoderQuotedPrintable.TIdEncoderQuotedPrintable, IdCoderUUE.TIdDecoderUUE, IdCoderUUE.TIdEncoderUUE, IdCoderXXE.TIdDecoderXXE, IdCoderXXE.TIdEncoderXXE, IdCompressorZLibEx.TIdCompressorZLibEx, IdConnectThroughHttpProxy.TIdConnectThroughHttpProxy, IdCookieManager.TIdCookieManager, IdDateTimeStamp.TIdDateTimeStamp, IdDayTime.TIdDayTime, IdDayTimeServer.TIdDayTimeServer, IdDayTimeUDP.TIdDayTimeUDP, IdDayTimeUDPServer.TIdDayTimeUDPServer, IdDICT.TIdDICT, IdDICTServer.TIdDICTServer, IdDiscardServer.TIdDISCARDServer, IdDiscardUDPServer.TIdDiscardUDPServer, IdDNSResolver.TIdDNSResolver, IdDNSServer.TIdDNSServer, IdEcho.TIdEcho, IdEchoServer.TIdECHOServer, IdEchoUDP.TIdEchoUDP, IdEchoUDPServer.TIdEchoUDPServer, IdFinger.TIdFinger, IdFingerServer.TIdFingerServer, IdFTP.TIdFTP, IdFTPServer.TIdFTPServer, IdGopher.TIdGopher, IdGopherServer.TIdGopherServer, IdHTTP.TIdHTTP, IdHTTPProxyServer.TIdHTTPProxyServer, IdHTTPServer.TIdHTTPServer, IdIdent.TIdIdent, IdIdentServer.TIdIdentServer, IdIMAP4.TIdIMAP4, IdIMAP4Server.TIdIMAP4Server, IdIPMCastClient.TIdIPMCastClient, IdIPMCastServer.TIdIPMCastServer, IdIPWatch.TIdIPWatch, IdIRC.TIdIRC, IdIrcServer.TIdIRCServer, IdLPR.TIdLPR, IdMailBox.TIdMailBox, IdMappedFTP.TIdMappedFTP, IdMappedPOP3.TIdMappedPOP3, IdMappedPortTCP.TIdMappedPortTCP, IdMappedPortUDP.TIdMappedPortUDP, IdMappedTelnet.TIdMappedTelnet, IdMessage.TIdMessage, IdMessageCoderMIME.TIdMessageDecoderMIME, IdMessageCoderMIME.TIdMessageEncoderMIME, IdMessageCoderYenc.TIdMessageDecoderYenc, IdMessageCoderYenc.TIdMessageEncoderYenc, IdNetworkCalculator.TIdNetworkCalculator, IdNNTP.TIdNNTP, IdNNTPServer.TIdNNTPServer, IdPOP3.TIdPOP3, IdPOP3Server.TIdPOP3Server, IdQotd.TIdQOTD, IdQotdServer.TIdQOTDServer, IdQOTDUDP.TIdQOTDUDP, IdQOTDUDPServer.TIdQotdUDPServer, IdRexec.TIdRexec, IdRexecServer.TIdRexecServer, IdRSH.TIdRSH, IdRSHServer.TIdRSHServer, IdSASLAnonymous.TIdSASLAnonymous, IdSASLExternal.TIdSASLExternal, IdSASLLogin.TIdSASLLogin, IdSASLOTP.TIdSASLOTP, IdSASLPlain.TIdSASLPlain, IdSASLSKey.TIdSASLSKey, IdSASL_CRAM_MD5.TIdSASLCRAMMD5, IdServerInterceptLogEvent.TIdServerInterceptLogEvent, IdServerInterceptLogFile.TIdServerInterceptLogFile, IdSMTP.TIdSMTP, IdSMTPRelay.TIdSMTPRelay, IdSMTPServer.TIdSMTPServer, IdSNMP.TIdSNMP, IdSNPP.TIdSNPP, IdSNTP.TIdSNTP, IdSocksServer.TIdSocksServer, IdSSLOpenSSL.TIdServerIOHandlerSSLOpenSSL, IdSSLOpenSSL.TIdSSLIOHandlerSocketOpenSSL, IdSysLog.TIdSysLog, IdSysLogMessage.TIdSysLogMessage, IdSysLogServer.TIdSyslogServer, IdSystat.TIdSystat, IdSystatServer.TIdSystatServer, IdSystatUDP.TIdSystatUDP, IdSystatUDPServer.TIdSystatUDPServer, IdTelnet.TIdTelnet, IdTelnetServer.TIdTelnetServer, IdTime.TIdTime, IdTimeServer.TIdTimeServer, IdTimeUDP.TIdTimeUDP, IdTimeUDPServer.TIdTimeUDPServer, IdTrivialFTP.TIdTrivialFTP, IdTrivialFTPServer.TIdTrivialFTPServer, IdUserAccounts.TIdUserManager, IdUserPassProvider.TIdUserPassProvider, IdVCard.TIdVCard, IdWhois.TIdWhois, IdWhoIsServer.TIdWhoIsServer.

Cerraremos el IDE de Delphi, sin guardar cambios y volveremos a abrirlo para verificar que la instalación de las Indy 10 ha sido correcta. Deben aparecernos una serie de pestañas nuevas en la paleta de componentes: Indy Clients, Indy Servers, Indy Misc, Indy I/O Handlers, Indy Intercepts, Indy SASL:

Descargar e instalar Indy 10 en Borland Delphi 6

Descargar DLL de OpenSLL

Para el envío de correos electrónicos usando el protocolo TLS (antiguo SSL) necesitaremos, además de los componentes Indy 10, las librerías DLL OpenSSL, que podemos descargar de nuestro propio sitio web en el siguiente enlace:

Para este caso solo necesitaremos descomprimir el fichero openssl-1.0.2o-i386-win32.zip y copiar los ficheros ssleay32.dll y libeay32.dll a la carpeta donde tengamos el ejecutable de nuestra aplicación. No es necesario registrarlas ni instalar componentes adicionales, es suficiente con copiarlos a la carpeta donde esté el ejecutable de la aplicación.

Desarrollar aplicación ProyectoA Envío email TLS SSL en Delphi 6

Una vez instaladas las Indy 10 y descargado el paquete OpenSLL con sus dos librerías procederemos a desarrollar la aplicación Delphi que usará estos componentes para enviar correos electrónicos usando el protocolo TLS (sucesor del anterior SSL). La aplicación permitirá elegir el protocolo a usar y el tipo de autenticación, entre otras opciones de conexión.

Crear proyecto Delphi y añadir componentes visuales al formulario principal

Abriremos Delphi, crearemos un nuevo proyecto (menú «File» – «New» – «Application»). Añadiremos los componentes necesarios (cuadros de texto para solicitar los datos de acceso al servidor SMTP, desplegables, botones y demás, tal y como se muestra en las siguientes imágenes. Podéis descargar el código fuente completo y gratuito de la aplicación ProyectoA en el siguiente enlace:

Insertaremos un TPageControl para añadir las siguientes pestañas:

  • Envío de E-Mail: donde colocaremos los componentes necesarios para solicitar el destinatario, el CC, CCO, asunto, mensajee y adjuntos:
Desarrollar aplicación ProyectoA Envío email TLS SSL en Delphi 6
  • Datos conexión servidor SMTP: donde colocaremos los componentes necesarios para solicitar los datos de conexión al servidor SMTP, la dirección del servidor, si requerirá autenticación, usuario, contraseña, si se usará TLS o SSL y la versión, método de conexión TLS o SSL, puerto. También solicitaremos los datos del remitente: nombre y e-mail:
Desarrollar aplicación ProyectoA Envío email TLS SSL en Delphi 6
  • Resultado del envío: una última pestaña con un TMemo para mostrar el log de los procesos de envío de correo electrónico y el resultado de cada proceso:
Desarrollar aplicación ProyectoA Envío email TLS SSL en Delphi 6

Añadiremos un par de botones para enviar el e-mail y para cerrar la aplicación, como se puede ver en las imágenes anteriores.

Componentes no visuales para el envío de correo electrónico mediante TLS SSL

Añadiremos los siguientes componentes de la paleta de Indy, que serán los encargados de enviar el mail con los datos especificados. En primer lugar, desde la paleta «Indy Clients» añadiremos el componente IdSMTP:

Desarrollar aplicación ProyectoA Envío email TLS SSL en Delphi 6

Y en la pestaña «Indy I/O Handlers» añadiremos IdSSLIOHandlerSocketOpenSSL:

Desarrollar aplicación ProyectoA Envío email TLS SSL en Delphi 6

Para enlazar un componente con el otro, seleccionaremos el componente IdSMTP y en la propiedad IOHandler desplegaremos para seleccionar el componente anterior IdSSLIOHandlerSocketOpenSSL1:

Desarrollar aplicación ProyectoA Envío email TLS SSL en Delphi 6

De forma adicional, para seleccionar ficheros adjuntos (no es de Indy), añadiremos un OpenDialog de la pestaña «Dialogs»:

Desarrollar aplicación ProyectoA Envío email TLS SSL en Delphi 6

Código fuente en Delphi 6 para envío de E-Mail mediante TLS SSL con Indy 10 y OpenSSL

Una vez añadidos todos los componentes (visuales y no visuales), procederemos a escribir el código fuente necesario para la conexión con el servidor SMTP y el envío del correo electrónico con ficheros adjuntos. Es muy importante añadir la siguiente línea al evento OnCreate del formulario principal de la aplicación:

IdSSLOpenSSLHeaders.Load;

que será la que cargue las DLL necesarias de OpenSSL (ssleay32.dll y libeay32.dll) y que deben estar en la misma carpeta que el ejecutable de la aplicación.

Por supuesto, el código fuente completo (la apliación completa) está disponible gratuitamente en el siguiente enlace:

procedure TformEnvioEmailTLS.FormCreate(Sender: TObject);
var
  ficheroMensaje : string;
begin
  //Cargamos las DLL de OpenSSL
  IdSSLOpenSSLHeaders.Load;

  txtServidorSMTP.Text :=
      leCadINI('Conexión SMTP', 'Servidor SMTP', '');
  lsAutenticacion.ItemIndex :=
      lsAutenticacion.Items.IndexOf(leCadINI('Conexión SMTP', 'Autenticación', 'Defecto'));
  txtUsuario.Text :=
      leCadINI('Conexión SMTP', 'Usuario', '');
  txtContrasena.Text :=
      Trim (cifrarTexto(leCadINI('Conexión SMTP', 'Contraseña', ''), claveCifrado));
  lsTLS.ItemIndex :=
      lsTLS.Items.IndexOf(leCadINI('Conexión SMTP', 'TLS SSL', 'TLS explícito'));
  lsMetdoSSL.ItemIndex :=
      lsMetdoSSL.Items.IndexOf(leCadINI('Conexión SMTP', 'Método SSL', 'sslvSSLv3'));
  txtPuerto.Text :=
      inttostr(leEntINI('Conexión SMTP', 'Puerto', 587));
  txtRemitenteNombre.Text :=
      leCadINI('Conexión SMTP', 'Remitente - Nombre', '');
  txtRemitenteMail.Text :=
      leCadINI('Conexión SMTP', 'Remitente - EMail', '');

  txtDestinatario.Text :=
      leCadINI('Datos envío E-Mail', 'Destinatario', '');
  txtCC.Text :=
      leCadINI('Datos envío E-Mail', 'Destinatario CC', '');
  txtCCO.Text :=
      leCadINI('Datos envío E-Mail', 'Destinatario CCO', '');
  txtAsunto.Text :=
      leCadINI('Datos envío E-Mail', 'Asunto', '');

  ficheroMensaje :=
      IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName)) + 'mensaje.txt';
  if FileExists(ficheroMensaje) then
    txtMensaje.Lines.LoadFromFile(ficheroMensaje);
end;

En el código anterior, para el evento OnCreate, cargamos las DLL de OpenSSL con:

IdSSLOpenSSLHeaders.Load;

Y el resto del código se usa para cargar del fichero INI la configuración de la aplicación, para no tener que escribirla cada vez que la iniciemos: dirección del servidor SMTP, autenticación, usuario, contraseña (se encripta pero con un cifrado muy flojo y fácil de descubrir), TLS o SSL, método de conexión, puerto, nombre del remitente, mail del remitente, destinatario, CC, CCO, asunto y mensaje. Todos estos datos quedan guadados en un fichero INI EnvioEMailTLS.INI y en un fichero mensaje.txt y son cargados al iniciar la aplicación.

El código del botón Enviar (en el evento OnClick) será el siguiente:

procedure TformEnvioEmailTLS.btEnviarMailClick(Sender: TObject);
var
  mail : TIdMessage;
  adjuntos : TStrings;
  i : integer;
begin
  if txtServidorSMTP.Text = '' then
  begin
    MessageDlg ('Debe indicar el la dirección del servidor de SMTP.', mtWarning, [mbok], 0);
    tabDatos.Show;
    txtServidorSMTP.SetFocus;
    exit;
  end;
  if (lsAutenticacion.Text <> 'Ninguna') and ((txtUsuario.Text = '') or (txtContrasena.Text = '')) then
  begin
    MessageDlg ('Debe indicar el usuario y contraseña de autenticación del servidor SMTP.', mtWarning, [mbok], 0);
    tabDatos.Show;
    txtUsuario.SetFocus;
    exit;
  end;
  if lsTLS.Text = '' then
  begin
    MessageDlg ('Debe indicar si requiere TLS / SSL.', mtWarning, [mbok], 0);
    tabDatos.Show;
    lsTLS.SetFocus;
    exit;
  end;
  if txtPuerto.Text = '' then
  begin
    MessageDlg ('Debe indicar el puerto de envío de mail (por defecto para TLS ' +
        'es 587 y sin TLS es 25).', mtWarning, [mbok], 0);
    tabDatos.Show;
    txtPuerto.SetFocus;
    exit;
  end;
  if txtRemitenteNombre.Text = '' then
  begin
    MessageDlg ('Debe indicar el nombre del remitente.', mtWarning, [mbok], 0);
    tabDatos.Show;
    txtRemitenteNombre.SetFocus;
    exit;
  end;
  if txtRemitenteMail.Text = '' then
  begin
    MessageDlg ('Debe indicar el e-mail del remitente.', mtWarning, [mbok], 0);
    tabDatos.Show;
    txtRemitenteMail.SetFocus;
    exit;
  end;
  if txtDestinatario.Text = '' then
  begin
    MessageDlg ('Debe indicar el e-mail del destinatario (para varios mails separar con comas).',
        mtWarning, [mbok], 0);
    tabEnviarMail.Show;
    txtDestinatario.SetFocus;
    exit;
  end;
  if txtAsunto.Text = '' then
  begin
    MessageDlg ('Debe indicar el asunto del correo electrónico.', mtWarning, [mbok], 0);
    tabEnviarMail.Show;
    txtAsunto.SetFocus;
    exit;
  end;
  if txtMensaje.Text = '' then
  begin
    MessageDlg ('Debe indicar el cuerpo del correo electrónico.', mtWarning, [mbok], 0);
    tabEnviarMail.Show;
    txtMensaje.SetFocus;
    exit;
  end;
  if (pos('adjunto', AnsiLowerCase(txtMensaje.Text)) > 0) and (lFicherosAdjuntos.Count = 0) then
  begin
    if MessageDlg ('Ha introducido la palabra "adjunto" en el cuerpo pero no ha adjuntado documentos ' +
        'al correo electrónico ¿Desea continuar con el envío sin adjuntos?',
        mtConfirmation, [mbYes, mbNo], 0) = mrno then
    begin
      tabEnviarMail.Show;
      lFicherosAdjuntos.SetFocus;
      exit;
    end;
  end;

  //Si no está conectado al servidor SMTP conectar
 // if not idSMTP.Connected then
 // begin
    with idSMTP do
    begin
      if lsMetdoSSL.Text = 'sslvTLSv1' then
        IdSSLIOHandlerSocketOpenSSL1.SSLOptions.Method := sslvTLSv1;
      if lsMetdoSSL.Text = 'sslvTLSv2' then
        IdSSLIOHandlerSocketOpenSSL1.SSLOptions.Method := sslvSSLv2;
      if lsMetdoSSL.Text = 'sslvTLSv23' then
        IdSSLIOHandlerSocketOpenSSL1.SSLOptions.Method := sslvSSLv23;
      if lsMetdoSSL.Text = 'sslvTLSv3' then
        IdSSLIOHandlerSocketOpenSSL1.SSLOptions.Method := sslvSSLv3;

      IoHandler := IdSSLIOHandlerSocketOpenSSL1;

      //Tipo de autenticación
      if lsAutenticacion.Text = 'Defecto' then
        AuthType := atDefault;
      if lsAutenticacion.Text = 'Ninguna' then
        AuthType := atNone;
      if lsAutenticacion.Text = 'SASL' then
        AuthType := atSASL;
      //Si se requiere autenticación para el envío indicar usuario y contraseña
      Username := txtUsuario.Text;
      Password := txtContrasena.Text;
      Host := txtServidorSMTP.Text;
      //Usar TLS SLL para el envío
      if lsTLS.Text = 'TLS explícito' then
        useTLS := utUseExplicitTLS;
      if lsTLS.Text = 'Sin soporte TLS' then
        useTLS := utNoTLSSupport;
      if lsTLS.Text = 'TLS implícito' then
        useTLS := utUseExplicitTLS;
      if lsTLS.Text = 'TLS requerido' then
        useTLS := utUseExplicitTLS;
      //Puerto que se usará para la conexión con el servidor SMTP, en el caso de TLS el de defecto es 587
      port := strtoint(txtPuerto.Text);
    end;
    try
      txtResultado.Lines.add(DateTimeToStr(now) + ' Conectando con el servidor ' + txtServidorSMTP.Text);
      idSMTP.Connect;
      txtResultado.Lines.add(DateTimeToStr(now) + ' Conectado a ' + txtServidorSMTP.Text);
    except
      on e : exception do
      begin
        txtResultado.Lines.add(DateTimeToStr(now) + ' Error al conectar al servidor SMTP. ' + e.ClassName + ' ' + e.Message);
        MessageDlg('Error al conectar con servidor SMTP: ' + e.Message, mtError, [mbok], 0);
      end;
    end;
  //end;

  mail := TIdMessage.Create(Self);
  with mail do
  begin
    From.Name :=  txtRemitenteNombre.Text;
    From.Address := txtRemitenteMail.Text;
    Recipients.EMailAddresses := txtDestinatario.Text;
    CCList.EMailAddresses := txtCC.Text;
    BccList.EMailAddresses := txtCCO.Text;
    Subject := txtAsunto.Text;
    body.Text := txtMensaje.Text;

    //Cargar ficheros adjuntos seleccionados
    adjuntos := lFicherosAdjuntos.Items;
    for i := 0 to adjuntos.Count - 1 do
    begin
      if FileExists(adjuntos.Strings[i]) then
        TIdAttachmentFile.Create(MessageParts, adjuntos.Strings[i]);
    end;
  end;
  try
    idSMTP.Send(mail);
    txtResultado.Lines.add(DateTimeToStr(now) + ' Mensaje enviado correctamente');
    MessageDlg('Mensaje enviado correctamente.', mtInformation, [mbok], 0);
    if idSMTP.Connected then
      idSMTP.Disconnect;   
  except
    on e : exception do
    begin
      txtResultado.Lines.add(DateTimeToStr(now) + ' Error al enviar mensaje. ' + e.ClassName + ' ' + e.Message);
      MessageDlg('Error al enviar e-mail: ' + e.Message, mtError, [mbok], 0);
      if idSMTP.Connected then
        idSMTP.Disconnect;
    end;
  end;

Teniendo en cuenta que usará las siguientes funciones y procedimientos que también deben estar incluidas en la unidad del formulario principal:

implementation

const
  claveCifrado = -96;

{$R *.dfm}

//Codificado simple de cadena de texto
function cifrarTexto (const strText: string; const intKey: longint): string;
var
  i: integer;
  strResult: string;
begin
  // initialize result
  strResult := strText;

  // sync RandSeed key to generate Random chars
  RandSeed := intKey;

  // cipher
  for i := 1 to Length(strText) do
    strResult[i] := Chr(Ord(strResult[i]) xor Random(255));

  // set results
  cifrarTexto := strResult;
end;

//Decodificar cadena de texto
function descifrarTexto (const strText: string; const intKey: longint): string;
begin
  // deciphers the string
  descifrarTexto := cifrarTexto(strText, intKey);
end;

//Lee un booleano de un INI
function leBoolINI (clave, cadena : string; defecto : boolean) : boolean;
begin
  with tinifile.create (changefileext(paramstr(0),'.INI')) do
  try
    result := readbool (clave, cadena, defecto);
  finally
    free;
  end;
end;


//Lee un entero de un INI
function leEntINI (clave, cadena : string; defecto : integer) : integer;
begin
  with tinifile.create (changefileext(paramstr(0),'.INI')) do
  try
    result := readInteger (clave, cadena, defecto);
  finally
    free;
  end;
end;


//Lee una cadena de texto de un INI
function leCadINI (clave, cadena : string; defecto : string) : string;
begin
  with tinifile.create (changefileext(paramstr(0),'.INI')) do
  try
    result := readString (clave, cadena, defecto);
  finally
    free;
  end;
end;

//lee una fecha de un INI
function leFechaINI (clave, cadena : string; defecto : tdatetime) : tdatetime;
begin
  with tinifile.create (changefileext(paramstr(0),'.INI')) do
  try
    result := ReadDate (clave, cadena, defecto);
  finally
    free;
  end;
end;

//lee un valor numérico de un INI
function leFloatINI (clave, cadena : string; defecto : double) : double;
begin
  with tinifile.create (changefileext(paramstr(0),'.INI')) do
  try
    result := readfloat (clave, cadena, defecto);
  finally
    free;
  end;
end;


//escribe un Booleano en un INI
procedure esBoolINI (clave, cadena : string; valor : boolean);
begin
  with tinifile.create (changefileext(paramstr(0),'.INI')) do
  try
    writeBool (clave, cadena, valor);
  finally
    free;
  end;
end;


//Escribe un entero en un INI
procedure esEntINI (clave, cadena : string; valor : integer);
begin
  with tinifile.create (changefileext(paramstr(0),'.INI')) do
  try
    writeInteger (clave, cadena, valor);
  finally
    free;
  end;
end;


//escribe una cadena de texto en un INI
procedure esCadINI (clave, cadena, valor : string);
begin
  with tinifile.create (changefileext(paramstr(0),'.INI')) do
  try
    writeString (clave, cadena, valor);
  finally
    free;
  end;
end;


//escribe un número en un INI
procedure esFloatINI (clave, cadena : string; valor : double);
begin
  with tinifile.create (changefileext(paramstr(0),'.INI')) do
  try
    WriteFloat (clave, cadena, valor);
  finally
    free;
  end;
end;


//escribe una fecha en un INI
procedure esFechaINI (clave, cadena : string; defecto : tdatetime);
begin
  with tinifile.create (changefileext(paramstr(0),'.INI')) do
  try
    WriteDate (clave, cadena, defecto);
  finally
    free;
  end;
end;

function tamanoFichero (sFileToExamine: string) : Integer;
var
  SearchRec: TSearchRec;
  sgPath: string;
  inRetval, I1: Integer;
begin
  sgPath := ExpandFileName(sFileToExamine);
  try
    inRetval := FindFirst(ExpandFileName(sFileToExamine), faAnyFile, SearchRec);
    if inRetval = 0 then
      I1 := SearchRec.Size
    else
      I1 := -1;
  finally
    SysUtils.FindClose(SearchRec);
  end;
  Result := I1;
end;


function existeElementoListBox (elemento : string; lista : TListBox) : integer;
var
  i : integer;
begin
  existeElementoListBox := -1;

  for i := 0 to lista.Count - 1 do
  begin
    if AnsiUpperCase (lista.items[i]) = AnsiUpperCase (elemento) then
    begin
      existeElementoListBox := i;
      Exit;
    end;
  end;
end;

procedure TformEnvioEmailTLS.tamanoFicherosAdjuntos ();
var
  i : integer;
  tamano : integer;
begin
  tamano := 0;
  for i := 0 to lFicherosAdjuntos.Count - 1 do
  begin
    tamano := tamano + tamanoFichero (lFicherosAdjuntos.Items[i]);
  end;
  if tamano > 0 then
    lTamanoAdjuntos.Caption := 'Tamaño ficheros adjuntos: ' +
        FormatFloat ('###,###,###,##0.00 MB;-###,###,###,##0.00 MB;0',
         tamano/1024/1024)
  else
    lTamanoAdjuntos.Caption := 'Tamaño ficheros adjuntos: --';
end;

En el evento OnClose, para cuando se cierra la aplicación, añadiremos el siguiente código:

procedure TformEnvioEmailTLS.FormClose(Sender: TObject;
  var Action: TCloseAction);
var
  ficheroMensaje : string;
begin
  esCadINI('Conexión SMTP', 'Servidor SMTP', txtServidorSMTP.Text);
  esCadINI('Conexión SMTP', 'Autenticación', lsAutenticacion.Text);
  esCadINI('Conexión SMTP', 'Usuario', txtUsuario.Text);
  esCadINI('Conexión SMTP', 'Contraseña', cifrarTexto(txtContrasena.Text, claveCifrado));
  esCadINI('Conexión SMTP', 'TLS SSL', lsTLS.Text);
  esCadINI('Conexión SMTP', 'Método SSL', lsMetdoSSL.Text);
  esEntINI('Conexión SMTP', 'Puerto', strtoint(txtPuerto.Text));
  esCadINI('Conexión SMTP', 'Remitente - Nombre', txtRemitenteNombre.Text);
  esCadINI('Conexión SMTP', 'Remitente - EMail', txtRemitenteMail.Text);
  txtMensaje.Lines.SaveToFile(IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName)) + 'mensaje.txt');  

  esCadINI('Datos envío E-Mail', 'Destinatario', txtDestinatario.Text);
  esCadINI('Datos envío E-Mail', 'Destinatario CC', txtCC.Text);
  esCadINI('Datos envío E-Mail', 'Destinatario CCO', txtCCO.Text);
  esCadINI('Datos envío E-Mail', 'Asunto', txtAsunto.Text);

  ficheroMensaje :=
      IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName)) + 'mensaje.txt';
  if FileExists(ficheroMensaje) then
    txtMensaje.Lines.LoadFromFile(ficheroMensaje);

  {
  try
    if idSMTP.Connected then
      idSMTP.Disconnect;
  finally
  end;
  }
end;

Que básicamente guardará todos los valores introducidos en el envío del último correo electrónico y los valores de configuración en un fichero INI, como hemos dicho anteriormente, para no tener que escribirla cada vez que la iniciemos.

Para los botones de añadir y quitar ficheros adjuntos añadiremos el siguiente código a sus respectivos eventos OnClick:

procedure TformEnvioEmailTLS.btAdjuntarClick(Sender: TObject);
begin
  if dlSelAdjunto.execute then
  begin
    if existeElementoListBox(dlSelAdjunto.FileName, lFicherosAdjuntos) = -1 then
    begin
      lFicherosAdjuntos.items.add (dlSelAdjunto.filename);
      tamanoFicherosAdjuntos;
    end
    else
      MessageDlg('Ya ha adjuntado este fichero anteriormente.', mtInformation, [mbok], 0);
  end;
end;

procedure TformEnvioEmailTLS.btQuitarAdjuntoClick(Sender: TObject);
begin
  if lFicherosAdjuntos.ItemIndex = -1 then
    MessageDlg('Debe seleccionar el fichero adjunto a quitar de la selección.',
        mtWarning, [mbok], 0)
  else
  begin
    lFicherosAdjuntos.items.delete(lFicherosAdjuntos.itemindex);
    tamanoFicherosAdjuntos;
  end;
end;

Anexo – Código fuente completo de la unidad UnidadEnvioEmailTLS

A continuación listamos el código fuente completo de la unidad UnidadEnvioEmailTLS que es donde se realizan todos los procesos de conexión con el servidor SMTP y envío de mail. Tenéis disponible de forma gratuita la aplicación y su código fuente en:

unit UnidadEnvioEmailTLS;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Buttons, IdSASLAnonymous, IdSASLExternal, IdSASLLogin,
  IdSASLOTP, IdSASLSKey, IdUserPassProvider, IdSASL, IdSASLUserPass,
  IdSASL_CRAM_MD5, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL,
  IdSSLOpenSSL, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient,
  IdExplicitTLSClientServerBase, IdMessageClient, IdSMTPBase, IdSMTP, idMessage,
  IdSASLPlain, IdSSLOpenSSLHeaders, IdAttachmentFile, ComCtrls, IniFiles,
  ExtCtrls, shellapi;

type
  TformEnvioEmailTLS = class(TForm)
    btEnviarMail: TBitBtn;
    idSMTP: TIdSMTP;
    IdSSLIOHandlerSocketOpenSSL1: TIdSSLIOHandlerSocketOpenSSL;
    dlSelAdjunto: TOpenDialog;
    PageControl1: TPageControl;
    tabEnviarMail: TTabSheet;
    tabDatos: TTabSheet;
    tabResultado: TTabSheet;
    GroupBox1: TGroupBox;
    Label1: TLabel;
    Label3: TLabel;
    Label4: TLabel;
    Label5: TLabel;
    Label6: TLabel;
    Label2: TLabel;
    Label12: TLabel;
    txtServidorSMTP: TEdit;
    lsAutenticacion: TComboBox;
    txtUsuario: TEdit;
    txtContrasena: TEdit;
    lsTLS: TComboBox;
    txtPuerto: TEdit;
    lsMetdoSSL: TComboBox;
    GroupBox2: TGroupBox;
    Label7: TLabel;
    Label8: TLabel;
    Label11: TLabel;
    Label13: TLabel;
    Label14: TLabel;
    txtDestinatario: TEdit;
    txtAsunto: TEdit;
    txtMensaje: TMemo;
    txtCC: TEdit;
    txtCCO: TEdit;
    GroupBox4: TGroupBox;
    lTamanoAdjuntos: TLabel;
    btAdjuntar: TBitBtn;
    btQuitarAdjunto: TBitBtn;
    txtResultado: TMemo;
    GroupBox3: TGroupBox;
    Label9: TLabel;
    txtRemitenteNombre: TEdit;
    txtRemitenteMail: TEdit;
    Label10: TLabel;
    btCerrar: TBitBtn;
    lFicherosAdjuntos: TListBox;
    TabSheet1: TTabSheet;
    Label17: TLabel;
    lForos: TLabel;
    Label18: TLabel;
    Label19: TLabel;
    Shape1: TShape;
    lPrograma: TLabel;
    lVersion: TLabel;
    txtInfo: TMemo;
    Shape2: TShape;
    Shape3: TShape;
    Label15: TLabel;
    Label16: TLabel;
    procedure btEnviarMailClick(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure FormCreate(Sender: TObject);
    procedure btAdjuntarClick(Sender: TObject);
    procedure btQuitarAdjuntoClick(Sender: TObject);
    procedure tamanoFicherosAdjuntos ();
    procedure lFicherosAdjuntosKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure idSMTPStatus(ASender: TObject; const AStatus: TIdStatus;
      const AStatusText: String);
    procedure btCerrarClick(Sender: TObject);
    procedure Label16Click(Sender: TObject);
    procedure lForosClick(Sender: TObject);
    procedure Label18Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  formEnvioEmailTLS: TformEnvioEmailTLS;

implementation

const
  claveCifrado = -96;

{$R *.dfm}

//Codificado simple de cadena de texto
function cifrarTexto (const strText: string; const intKey: longint): string;
var
  i: integer;
  strResult: string;
begin
  // initialize result
  strResult := strText;

  // sync RandSeed key to generate Random chars
  RandSeed := intKey;

  // cipher
  for i := 1 to Length(strText) do
    strResult[i] := Chr(Ord(strResult[i]) xor Random(255));

  // set results
  cifrarTexto := strResult;
end;

//Decodificar cadena de texto
function descifrarTexto (const strText: string; const intKey: longint): string;
begin
  // deciphers the string
  descifrarTexto := cifrarTexto(strText, intKey);
end;

//Lee un booleano de un INI
function leBoolINI (clave, cadena : string; defecto : boolean) : boolean;
begin
  with tinifile.create (changefileext(paramstr(0),'.INI')) do
  try
    result := readbool (clave, cadena, defecto);
  finally
    free;
  end;
end;


//Lee un entero de un INI
function leEntINI (clave, cadena : string; defecto : integer) : integer;
begin
  with tinifile.create (changefileext(paramstr(0),'.INI')) do
  try
    result := readInteger (clave, cadena, defecto);
  finally
    free;
  end;
end;


//Lee una cadena de texto de un INI
function leCadINI (clave, cadena : string; defecto : string) : string;
begin
  with tinifile.create (changefileext(paramstr(0),'.INI')) do
  try
    result := readString (clave, cadena, defecto);
  finally
    free;
  end;
end;

//lee una fecha de un INI
function leFechaINI (clave, cadena : string; defecto : tdatetime) : tdatetime;
begin
  with tinifile.create (changefileext(paramstr(0),'.INI')) do
  try
    result := ReadDate (clave, cadena, defecto);
  finally
    free;
  end;
end;

//lee un valor numérico de un INI
function leFloatINI (clave, cadena : string; defecto : double) : double;
begin
  with tinifile.create (changefileext(paramstr(0),'.INI')) do
  try
    result := readfloat (clave, cadena, defecto);
  finally
    free;
  end;
end;


//escribe un Booleano en un INI
procedure esBoolINI (clave, cadena : string; valor : boolean);
begin
  with tinifile.create (changefileext(paramstr(0),'.INI')) do
  try
    writeBool (clave, cadena, valor);
  finally
    free;
  end;
end;


//Escribe un entero en un INI
procedure esEntINI (clave, cadena : string; valor : integer);
begin
  with tinifile.create (changefileext(paramstr(0),'.INI')) do
  try
    writeInteger (clave, cadena, valor);
  finally
    free;
  end;
end;


//escribe una cadena de texto en un INI
procedure esCadINI (clave, cadena, valor : string);
begin
  with tinifile.create (changefileext(paramstr(0),'.INI')) do
  try
    writeString (clave, cadena, valor);
  finally
    free;
  end;
end;


//escribe un número en un INI
procedure esFloatINI (clave, cadena : string; valor : double);
begin
  with tinifile.create (changefileext(paramstr(0),'.INI')) do
  try
    WriteFloat (clave, cadena, valor);
  finally
    free;
  end;
end;


//escribe una fecha en un INI
procedure esFechaINI (clave, cadena : string; defecto : tdatetime);
begin
  with tinifile.create (changefileext(paramstr(0),'.INI')) do
  try
    WriteDate (clave, cadena, defecto);
  finally
    free;
  end;
end;

function tamanoFichero (sFileToExamine: string) : Integer;
var
  SearchRec: TSearchRec;
  sgPath: string;
  inRetval, I1: Integer;
begin
  sgPath := ExpandFileName(sFileToExamine);
  try
    inRetval := FindFirst(ExpandFileName(sFileToExamine), faAnyFile, SearchRec);
    if inRetval = 0 then
      I1 := SearchRec.Size
    else
      I1 := -1;
  finally
    SysUtils.FindClose(SearchRec);
  end;
  Result := I1;
end;


function existeElementoListBox (elemento : string; lista : TListBox) : integer;
var
  i : integer;
begin
  existeElementoListBox := -1;

  for i := 0 to lista.Count - 1 do
  begin
    if AnsiUpperCase (lista.items[i]) = AnsiUpperCase (elemento) then
    begin
      existeElementoListBox := i;
      Exit;
    end;
  end;
end;

procedure TformEnvioEmailTLS.tamanoFicherosAdjuntos ();
var
  i : integer;
  tamano : integer;
begin
  tamano := 0;
  for i := 0 to lFicherosAdjuntos.Count - 1 do
  begin
    tamano := tamano + tamanoFichero (lFicherosAdjuntos.Items[i]);
  end;
  if tamano > 0 then
    lTamanoAdjuntos.Caption := 'Tamaño ficheros adjuntos: ' +
        FormatFloat ('###,###,###,##0.00 MB;-###,###,###,##0.00 MB;0',
         tamano/1024/1024)
  else
    lTamanoAdjuntos.Caption := 'Tamaño ficheros adjuntos: --';
end;

procedure TformEnvioEmailTLS.btEnviarMailClick(Sender: TObject);
var
  mail : TIdMessage;
  adjuntos : TStrings;
  i : integer;
begin
  if txtServidorSMTP.Text = '' then
  begin
    MessageDlg ('Debe indicar el la dirección del servidor de SMTP.', mtWarning, [mbok], 0);
    tabDatos.Show;
    txtServidorSMTP.SetFocus;
    exit;
  end;
  if (lsAutenticacion.Text <> 'Ninguna') and ((txtUsuario.Text = '') or (txtContrasena.Text = '')) then
  begin
    MessageDlg ('Debe indicar el usuario y contraseña de autenticación del servidor SMTP.', mtWarning, [mbok], 0);
    tabDatos.Show;
    txtUsuario.SetFocus;
    exit;
  end;
  if lsTLS.Text = '' then
  begin
    MessageDlg ('Debe indicar si requiere TLS / SSL.', mtWarning, [mbok], 0);
    tabDatos.Show;
    lsTLS.SetFocus;
    exit;
  end;
  if txtPuerto.Text = '' then
  begin
    MessageDlg ('Debe indicar el puerto de envío de mail (por defecto para TLS ' +
        'es 587 y sin TLS es 25).', mtWarning, [mbok], 0);
    tabDatos.Show;
    txtPuerto.SetFocus;
    exit;
  end;
  if txtRemitenteNombre.Text = '' then
  begin
    MessageDlg ('Debe indicar el nombre del remitente.', mtWarning, [mbok], 0);
    tabDatos.Show;
    txtRemitenteNombre.SetFocus;
    exit;
  end;
  if txtRemitenteMail.Text = '' then
  begin
    MessageDlg ('Debe indicar el e-mail del remitente.', mtWarning, [mbok], 0);
    tabDatos.Show;
    txtRemitenteMail.SetFocus;
    exit;
  end;
  if txtDestinatario.Text = '' then
  begin
    MessageDlg ('Debe indicar el e-mail del destinatario (para varios mails separar con comas).',
        mtWarning, [mbok], 0);
    tabEnviarMail.Show;
    txtDestinatario.SetFocus;
    exit;
  end;
  if txtAsunto.Text = '' then
  begin
    MessageDlg ('Debe indicar el asunto del correo electrónico.', mtWarning, [mbok], 0);
    tabEnviarMail.Show;
    txtAsunto.SetFocus;
    exit;
  end;
  if txtMensaje.Text = '' then
  begin
    MessageDlg ('Debe indicar el cuerpo del correo electrónico.', mtWarning, [mbok], 0);
    tabEnviarMail.Show;
    txtMensaje.SetFocus;
    exit;
  end;
  if (pos('adjunto', AnsiLowerCase(txtMensaje.Text)) > 0) and (lFicherosAdjuntos.Count = 0) then
  begin
    if MessageDlg ('Ha introducido la palabra "adjunto" en el cuerpo pero no ha adjuntado documentos ' +
        'al correo electrónico ¿Desea continuar con el envío sin adjuntos?',
        mtConfirmation, [mbYes, mbNo], 0) = mrno then
    begin
      tabEnviarMail.Show;
      lFicherosAdjuntos.SetFocus;
      exit;
    end;
  end;

  //Si no está conectado al servidor SMTP conectar
 // if not idSMTP.Connected then
 // begin
    with idSMTP do
    begin
      if lsMetdoSSL.Text = 'sslvTLSv1' then
        IdSSLIOHandlerSocketOpenSSL1.SSLOptions.Method := sslvTLSv1;
      if lsMetdoSSL.Text = 'sslvTLSv2' then
        IdSSLIOHandlerSocketOpenSSL1.SSLOptions.Method := sslvSSLv2;
      if lsMetdoSSL.Text = 'sslvTLSv23' then
        IdSSLIOHandlerSocketOpenSSL1.SSLOptions.Method := sslvSSLv23;
      if lsMetdoSSL.Text = 'sslvTLSv3' then
        IdSSLIOHandlerSocketOpenSSL1.SSLOptions.Method := sslvSSLv3;

      IoHandler := IdSSLIOHandlerSocketOpenSSL1;

      //Tipo de autenticación
      if lsAutenticacion.Text = 'Defecto' then
        AuthType := atDefault;
      if lsAutenticacion.Text = 'Ninguna' then
        AuthType := atNone;
      if lsAutenticacion.Text = 'SASL' then
        AuthType := atSASL;
      //Si se requiere autenticación para el envío indicar usuario y contraseña
      Username := txtUsuario.Text;
      Password := txtContrasena.Text;
      Host := txtServidorSMTP.Text;
      //Usar TLS SLL para el envío
      if lsTLS.Text = 'TLS explícito' then
        useTLS := utUseExplicitTLS;
      if lsTLS.Text = 'Sin soporte TLS' then
        useTLS := utNoTLSSupport;
      if lsTLS.Text = 'TLS implícito' then
        useTLS := utUseExplicitTLS;
      if lsTLS.Text = 'TLS requerido' then
        useTLS := utUseExplicitTLS;
      //Puerto que se usará para la conexión con el servidor SMTP, en el caso de TLS el de defecto es 587
      port := strtoint(txtPuerto.Text);
    end;
    try
      txtResultado.Lines.add(DateTimeToStr(now) + ' Conectando con el servidor ' + txtServidorSMTP.Text);
      idSMTP.Connect;
      txtResultado.Lines.add(DateTimeToStr(now) + ' Conectado a ' + txtServidorSMTP.Text);
    except
      on e : exception do
      begin
        txtResultado.Lines.add(DateTimeToStr(now) + ' Error al conectar al servidor SMTP. ' + e.ClassName + ' ' + e.Message);
        MessageDlg('Error al conectar con servidor SMTP: ' + e.Message, mtError, [mbok], 0);
      end;
    end;
  //end;

  mail := TIdMessage.Create(Self);
  with mail do
  begin
    From.Name :=  txtRemitenteNombre.Text;
    From.Address := txtRemitenteMail.Text;
    Recipients.EMailAddresses := txtDestinatario.Text;
    CCList.EMailAddresses := txtCC.Text;
    BccList.EMailAddresses := txtCCO.Text;
    Subject := txtAsunto.Text;
    body.Text := txtMensaje.Text;

    //Cargar ficheros adjuntos seleccionados
    adjuntos := lFicherosAdjuntos.Items;
    for i := 0 to adjuntos.Count - 1 do
    begin
      if FileExists(adjuntos.Strings[i]) then
        TIdAttachmentFile.Create(MessageParts, adjuntos.Strings[i]);
    end;
  end;
  try
    idSMTP.Send(mail);
    txtResultado.Lines.add(DateTimeToStr(now) + ' Mensaje enviado correctamente');
    MessageDlg('Mensaje enviado correctamente.', mtInformation, [mbok], 0);
    if idSMTP.Connected then
      idSMTP.Disconnect;   
  except
    on e : exception do
    begin
      txtResultado.Lines.add(DateTimeToStr(now) + ' Error al enviar mensaje. ' + e.ClassName + ' ' + e.Message);
      MessageDlg('Error al enviar e-mail: ' + e.Message, mtError, [mbok], 0);
      if idSMTP.Connected then
        idSMTP.Disconnect;
    end;
  end;
end;

procedure TformEnvioEmailTLS.FormClose(Sender: TObject;
  var Action: TCloseAction);
var
  ficheroMensaje : string;
begin
  esCadINI('Conexión SMTP', 'Servidor SMTP', txtServidorSMTP.Text);
  esCadINI('Conexión SMTP', 'Autenticación', lsAutenticacion.Text);
  esCadINI('Conexión SMTP', 'Usuario', txtUsuario.Text);
  esCadINI('Conexión SMTP', 'Contraseña', cifrarTexto(txtContrasena.Text, claveCifrado));
  esCadINI('Conexión SMTP', 'TLS SSL', lsTLS.Text);
  esCadINI('Conexión SMTP', 'Método SSL', lsMetdoSSL.Text);
  esEntINI('Conexión SMTP', 'Puerto', strtoint(txtPuerto.Text));
  esCadINI('Conexión SMTP', 'Remitente - Nombre', txtRemitenteNombre.Text);
  esCadINI('Conexión SMTP', 'Remitente - EMail', txtRemitenteMail.Text);
  txtMensaje.Lines.SaveToFile(IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName)) + 'mensaje.txt');  

  esCadINI('Datos envío E-Mail', 'Destinatario', txtDestinatario.Text);
  esCadINI('Datos envío E-Mail', 'Destinatario CC', txtCC.Text);
  esCadINI('Datos envío E-Mail', 'Destinatario CCO', txtCCO.Text);
  esCadINI('Datos envío E-Mail', 'Asunto', txtAsunto.Text);

  ficheroMensaje :=
      IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName)) + 'mensaje.txt';
  if FileExists(ficheroMensaje) then
    txtMensaje.Lines.LoadFromFile(ficheroMensaje);

  {
  try
    if idSMTP.Connected then
      idSMTP.Disconnect;
  finally
  end;
  }
end;

procedure TformEnvioEmailTLS.FormCreate(Sender: TObject);
var
  ficheroMensaje : string;
begin
  //Cargamos las DLL de OpenSSL
  IdSSLOpenSSLHeaders.Load;

  txtServidorSMTP.Text :=
      leCadINI('Conexión SMTP', 'Servidor SMTP', '');
  lsAutenticacion.ItemIndex :=
      lsAutenticacion.Items.IndexOf(leCadINI('Conexión SMTP', 'Autenticación', 'Defecto'));
  txtUsuario.Text :=
      leCadINI('Conexión SMTP', 'Usuario', '');
  txtContrasena.Text :=
      Trim (cifrarTexto(leCadINI('Conexión SMTP', 'Contraseña', ''), claveCifrado));
  lsTLS.ItemIndex :=
      lsTLS.Items.IndexOf(leCadINI('Conexión SMTP', 'TLS SSL', 'TLS explícito'));
  lsMetdoSSL.ItemIndex :=
      lsMetdoSSL.Items.IndexOf(leCadINI('Conexión SMTP', 'Método SSL', 'sslvSSLv3'));
  txtPuerto.Text :=
      inttostr(leEntINI('Conexión SMTP', 'Puerto', 587));
  txtRemitenteNombre.Text :=
      leCadINI('Conexión SMTP', 'Remitente - Nombre', '');
  txtRemitenteMail.Text :=
      leCadINI('Conexión SMTP', 'Remitente - EMail', '');

  txtDestinatario.Text :=
      leCadINI('Datos envío E-Mail', 'Destinatario', '');
  txtCC.Text :=
      leCadINI('Datos envío E-Mail', 'Destinatario CC', '');
  txtCCO.Text :=
      leCadINI('Datos envío E-Mail', 'Destinatario CCO', '');
  txtAsunto.Text :=
      leCadINI('Datos envío E-Mail', 'Asunto', '');

  ficheroMensaje :=
      IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName)) + 'mensaje.txt';
  if FileExists(ficheroMensaje) then
    txtMensaje.Lines.LoadFromFile(ficheroMensaje);
end;

procedure TformEnvioEmailTLS.btAdjuntarClick(Sender: TObject);
begin
  if dlSelAdjunto.execute then
  begin
    if existeElementoListBox(dlSelAdjunto.FileName, lFicherosAdjuntos) = -1 then
    begin
      lFicherosAdjuntos.items.add (dlSelAdjunto.filename);
      tamanoFicherosAdjuntos;
    end
    else
      MessageDlg('Ya ha adjuntado este fichero anteriormente.', mtInformation, [mbok], 0);
  end;
end;

procedure TformEnvioEmailTLS.btQuitarAdjuntoClick(Sender: TObject);
begin
  if lFicherosAdjuntos.ItemIndex = -1 then
    MessageDlg('Debe seleccionar el fichero adjunto a quitar de la selección.',
        mtWarning, [mbok], 0)
  else
  begin
    lFicherosAdjuntos.items.delete(lFicherosAdjuntos.itemindex);
    tamanoFicherosAdjuntos;
  end;
end;

procedure TformEnvioEmailTLS.lFicherosAdjuntosKeyDown(Sender: TObject;
  var Key: Word; Shift: TShiftState);
begin
  if key = VK_INSERT then
    btAdjuntarClick (nil);
  if key = VK_DELETE then
    btQuitarAdjuntoClick (nil);
end;

procedure TformEnvioEmailTLS.idSMTPStatus(ASender: TObject;
  const AStatus: TIdStatus; const AStatusText: String);
begin
  txtResultado.Lines.Add(DateTimeToStr(now) + ' ' +  AStatusText);
end;

procedure TformEnvioEmailTLS.btCerrarClick(Sender: TObject);
begin
  if MessageDlg('¿Desea cerrar la aplicación?', mtConfirmation, [mbyes,mbno], 0) = mryes then
    close;
end;

procedure TformEnvioEmailTLS.Label16Click(Sender: TObject);
begin
  ShellExecute(Handle, Nil, PChar('http://www.proyectoa.com'),
      Nil, Nil, SW_SHOWNORMAL);
end;

procedure TformEnvioEmailTLS.lForosClick(Sender: TObject);
begin
  ShellExecute(Handle, Nil, PChar('http://proyectoa.com/foros/foro/programas-proyecto-a/'),
      Nil, Nil, SW_SHOWNORMAL);
end;

procedure TformEnvioEmailTLS.Label18Click(Sender: TObject);
begin
  ShellExecute(Handle, Nil, PChar('http://www.proyectoa.com'),
      Nil, Nil, SW_SHOWNORMAL);
end;

end.