Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   Varios (https://www.clubdelphi.com/foros/forumdisplay.php?f=11)
-   -   Ssl Email (https://www.clubdelphi.com/foros/showthread.php?t=95333)

usuario1000 13-08-2021 12:26:02

Ssl Email
 
Buenas a todos.


Os escribo porque realicé un programa(Cliente-servidor en Delphi 10) hace ya algún tiempo y funcionaba perfectamente, llevo control de proveedores que me comunica por email, pero desde hace unos días para acá, no me llegan los emails. Revisando el codigo fuente, me da el error a la hora de ejecutar esta instrucción: SMTP.Connect; el error que me sale es "Could not load SSL Library".



Pego un poco del código fuente donde se ejecuta esto:


Código Delphi [-]
  SMTP := TIDsmtp.Create(nil);
  DATA := TIDMessage.Create(nil);
  SSL  := TIdSSLIOhandlerSocketOpenSSL.Create(nil);

  SSL.SSLOptions.Method := SSLVtlsv1;  //no sé si aquí debo tocar algo???
  SSL.SSLOptions.Mode := sslmUNassigned;
  SSL.SSLOptions.VerifyMode := [];
  SSL.SSLOptions.VerifyDepth:= 0;


  DATA.ContentType := 'text/plain';
  DATA.CharSet :=  'UTF-8';
  DATA.From.Address := 'correo@electronico.es';
  DATA.Recipients.EMailAddresses := destinatario; //destinatario;
  DATA.Subject := asunto;
  DATA.Body.Text := cuerpo;

  SMTP.IOHandler := SSL;
  SMTP.Host := 'smtp.servidor.com';
  SMTP.Port := 465;
  SMTP.Username := 'correo@electronico.es';
  SMTP.Password := 'contraseña';
  SMTP.UseTLS := utUseExplicitTLS;


 SMTP.Connect;  // aquí lanza el error.


Me urge muchísimo, porque lo utilizo en mi trabajo a diario para control a proveedores.


Agradeceria mucho cualquier tipo de información que me ayude a solventar este problema


He revisado hilos pero no me aclaran mucho.


Gracias a todos.

kuan-yiu 13-08-2021 12:54:22

¿Qué versión de la librería tienes? ¿La has actualizado recientemente? ¿La has movido de sitio?

PepCat 14-08-2021 09:39:59

Hola,

Por si te sirve de ayuda, adjunto esta clase para enviar emails desde una cuenta de gmail (puerto 465) que facilmente es adaptable a otro servicio de mail. No te olvides de incluir las librerias openSSL en la carpeta de tu ejecutable.

Código Delphi [-]

unit cfs.Email.gmail;

(*
   Step by Step :
  1. if you have not a gmail account, Create it.
  2. Important :
   -  Enter in your Personnal Setting (gmail) go to "Security":
      Activate “2-Step Verification” and add “App Password”
      or Activate "Allow less secure apps "
  3.  Add in your executable file path the two openSSL Libraries:  "libeay32.dll"  and  "ssleay32.dll"

  More info:
  http://delphiprogrammingdiary.blogsp...format-in.html
  http://www.andrecelestino.com/delphi...ponentes-indy/

*)

(*
  Use sample:

  Gmail := TGmail.Create('YourAccount@gmail.com', 'App password', 'From you/company');
  try
    try
      Gmail.Connect;
      Gmail.Send(['useremail@gmail.com'], 'Subject', 'PlainBody', 'htmlBody', 'AttachmentFile');
      Gmail.Send(...);
      Gmail.Send(...);
    except
      on E: Exception do
        ShowMessage(E.Message);
    end;
  finally
    GEmail.Free;
  end;
*)

interface

uses
  System.SysUtils, System.Classes, IdTCPConnection, IdExplicitTLSClientServerBase, IdMessageClient,  IdSMTP, IdMessage, IdIOHandler,
  IdBaseComponent, IdComponent, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, IdText, IdAttachmentFile;

type
  TcfsGmail = class
  private
    FFromName: string;
    FIdSSLIOHandlerSocket: TIdSSLIOHandlerSocketOpenSSL;
    FIdSMTP: TIdSMTP;
  public
    constructor Create(const UserName, Password, FromName: string);
    destructor Destroy; override;
    procedure Connect;
    procedure Send(ToAddresses: array of string; const Subject, PlainBody: string; const HTMLBody: string = ''; const AttachmentFile: string = '');
 end;

implementation


constructor TcfsGmail.Create(const UserName, Password, FromName: string);
begin
  FFromName := FromName;

  FIdSSLIOHandlerSocket := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
  FIdSSLIOHandlerSocket.SSLOptions.Method := sslvSSLv23;
  FIdSSLIOHandlerSocket.SSLOptions.Mode := sslmClient;
  FIdSSLIOHandlerSocket.SSLOptions.SSLVersions := [sslvTLSv1, sslvTLSv1_1, sslvTLSv1_2];

  FIdSMTP := TIdSMTP.Create(nil);
  FIdSMTP.IOHandler := FIdSSLIOHandlerSocket;
  FIdSMTP.UseTLS := utUseImplicitTLS;
  FIdSMTP.AuthType := satDefault;

  FIdSMTP.Host := 'smtp.gmail.com';
  FIdSMTP.Port := 465;

  FIdSMTP.Username := UserName;
  FIdSMTP.Password := Password;
end;

destructor TcfsGmail.Destroy;
begin
  if Assigned(FIdSMTP) then
  begin
    try
      FIdSMTP.Disconnect;
    except
    end;
    UnLoadOpenSSLLibrary;
    FreeAndNil(FIdSMTP);
  end;
  if Assigned(FIdSSLIOHandlerSocket) then
    FreeAndNil(FIdSSLIOHandlerSocket);

  inherited;
end;

procedure TcfsGmail.Connect;
begin
  FIdSMTP.Connect;
  FIdSMTP.Authenticate;
end;

procedure TcfsGmail.Send(ToAddresses: array of string; const Subject, PlainBody: string; const HTMLBody: string = ''; const AttachmentFile: string = '');
var
  IdMessage: TIdMessage;
  IdText: TIdText;
  Address: string;
  AttachFileExist: Boolean;
  MultipartAlternative: Boolean;
begin
  if not FIdSMTP.Connected then
    Connect;

  IdMessage := TIdMessage.Create(nil);
  try
    IdMessage.From.Address := FIdSMTP.Username;
    IdMessage.From.Name := FFromName;

    for Address in ToAddresses do
    begin
      if Address <> '' then
        IdMessage.Recipients.Add.Text := Address;
    end;

    IdMessage.Subject := Subject;

    AttachFileExist := False;
    if AttachmentFile <> '' then
      AttachFileExist := FileExists(AttachmentFile);

    MultipartAlternative := False;
    if (PlainBody <> '') and (HTMLBody <> '')  then
      MultipartAlternative := True;

    IdMessage.ContentType := 'multipart/alternative';
    if AttachFileExist then
    begin
      if MultipartAlternative then
        IdMessage.ContentType := 'multipart/related; type="multipart/alternative"'
      else
        IdMessage.ContentType := 'multipart/mixed';
    end;

    if MultipartAlternative and AttachFileExist then
    begin
      IdText := TIdText.Create(IdMessage.MessageParts);
      IdText.ContentType := 'multipart/alternative';
    end;

    // plain body
    if PlainBody <> '' then
    begin
      IdText := TIdText.Create(IdMessage.MessageParts);
      IdText.ContentType := 'text/plain; charset="UTF-8"';
      IdText.Body.Text := PlainBody;
      if MultipartAlternative and AttachFileExist then
        IdText.ParentPart := 0;
    end;

    // html body
    if HTMLBody <> '' then
    begin
      IdText := TIdText.Create(IdMessage.MessageParts);
      IdText.ContentType := 'text/html; charset="UTF-8"';
      IdText.Body.Text := HTMLBody;
      if MultipartAlternative and AttachFileExist then
        IdText.ParentPart := 0;
    end;

    if AttachFileExist then
      TIdAttachmentFile.Create(IdMessage.MessageParts, AttachmentFile);

    FIdSMTP.Send(IdMessage);
  finally
    IdMessage.Free;
  end;
end;

end.

usuario1000 15-08-2021 15:47:39

Cita:

Empezado por kuan-yiu (Mensaje 542333)
¿Qué versión de la librería tienes? ¿La has actualizado recientemente? ¿La has movido de sitio?

No he tocado nada, estaba el programa funcionando perfectamente y de pronto ha dejado de funcionar(la parte enviar email). Creo que se debe, por sospechar de algo, a una actualización de windows que se ha hecho recientemente.

usuario1000 15-08-2021 18:36:08

Solucionado!!!! muchisimas gracias, me ha servido mucho tu código. Enormemente agradecido.

usuario1000 15-08-2021 18:37:11

Muchas gracias a todos, lo he solucionado con el código de PepCat.



Enormemente agradecido.


Gracias y cuidense!!!!!


La franja horaria es GMT +2. Ahora son las 14:34:09.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi