Sending email using Gmail

Asked

Viewed 6,333 times

8

I need help emailing by Gmail using the Indy10 and Delphi 7. I think the Delphi version shouldn’t matter so much, but the right Indy version?

I slowly lowered the Indy10 down Indy.fulgan.com/ZIP/ and installed the components.

As Dll s I got from indy_openssl096.zip package inside the SSL.zip, in that directory. And I’m getting the following mistake:

Raised Exception class Eidosslcouldnotloadssllibrary with message 'Could not load SSL library.'

Now, when downloading the version openssl-1.0.0l-i386-Win32, in Indy.fulgan.com/SSL/ step to have the following error:

'RCPT first. d8sm5855899vek.11 - gsmtp'.

I am following the following example of Marco Cantu marcocantu.com/tips/oct06_gmail.

That is to say:

DFM of the components:

object IdMsg: TIdSMTP
    OnStatus = IdSMTP1Status
    IOHandler = IdSSLSocket
    Host = 'smtp.gmail.com'
    Port = 587
    SASLMechanisms = <>
    UseTLS = utUseExplicitTLS
    Username = '****@gmail.com'
    Password = '****'
end
object IdSSLSocket: TIdSSLIOHandlerSocketOpenSSL
    Destination = 'smtp.gmail.com:587'
    Host = 'smtp.gmail.com'
    MaxLineAction = maException
    Port = 587
    SSLOptions.Method = sslvTLSv1
    SSLOptions.Mode = sslmUnassigned
    SSLOptions.VerifyMode = []
    SSLOptions.VerifyDepth = 0
    OnStatusInfo = IdSSLSocketStatusInfo
end

Shipping method:

procedure TMainForm.enviarButtonClick(Sender: TObject);
begin
  IdMsg.Clear;
  IdMsg.ClearBody;
  IdMsg.ClearHeader;

  IdMsg.From.Address := '****@gmail.com';
  IdMsg.From.Name := 'NOME';

  IdMsg.Body.Text := 'Data/Hora: ' + DateTimeToStr(Now);
  IdMsg.Body.Add('Teste');

  IdSmtp.Connect();
  IdSmtp.Send(IdMsg);
  IdSmtp.Disconnect;
end;

So, after all, what am I doing wrong?

3 answers

8


Response derived from: Delphi 7 and gmail (connection with authentication)

Gmail uses encryption system , and to connect our application to it, we need two specific dll’s that would be:

libeay32.dll and ssleay32.dll. (download them can be found here)

After having the dll’s on hand, unzip them in the directory C:\WINDOWS\System32.

Insert the following components into the form: IdSMTP (palette Indy Clients), IdMessage(Indy Misc palette), IdSSLIOHandlerSocket (Indy I/O Handlers palette) and a Button.

To make it easier, rename the components to SMTP, MSG and Sslsocket, respectively.

Now on the Oncreate form:

procedure TForm1.FormCreate(Sender: TObject);
Begin
   with SMTP do
   begin
      AuthenticationType := atLogin;
      Host := 'smtp.gmail.com';
      IOHandler := SSLSocket;
      Password := 'sua senha no gmail';
      Port := 465;
      Username := '[email protected]'; //não esqueça o @gmail.com!!
  end;
  SSLSocket.SSLOptions.Method := sslvSSLv2;
  SSLSocket.SSLOptions.Mode := sslmClient;
end;

Simple example of use with a button:

procedure TForm1.Button1Click(Sender: TObject);
begin
  with MSG do
  begin
    Body.Add('corpo da mensagem');
    From.Address := 'email do remetente'; //opcional
    From.Name := 'nome do remetente'; //opcional
    Recipients.Add;
    Recipients.Items[0].Address := '[email protected]';
    Recipients.Items[0].Name := 'nome do destinatario'; //opcional
    Subject := 'assunto da mensagem';
  end;
  try
    SMTP.Connect();
    SMTP.Send(MSG);
    SMTP.Disconnect;
  except
    ShowMessage('Falha no envio!');
    exit;
  end;
  ShowMessage('Mensagem enviada com sucesso!');
end;
  • I think I’ve tried that example, but I’ll test..

  • Oops, I was kind of busy, but I’m gonna test it now. But at first, this one IdSSLIOHandlerSocket no longer has in Indy 10. What I have here is the IdSSLIOHandlerSocketOpenSSL. I’ll see if I can do it like this..

  • Strange.. I already changed the options of the Usetsl property of the component IdSMTP. I tried with the IdSSLIOHandlerSocketOpenSSL with host and port information and without that information.. but is always locking in the method Connect. The AuthType I had to leave as satDefault. SSLOptions.Method and Mode I left with the example, but did not give also.

  • I’ll raise another VM with Delphi7 and Indy9 to see if this example will.. but I still think I’ve tried this one already.

  • 2

    I use 7 with Indy 9, and here it worked right

  • 2

    Voted e +1. I did with the Indy 10 even following the same example I was doing. Oddly enough, I was forgetting to inform the property Recipient. Dear God!!! And thank you so much for your help!

Show 1 more comment

0

// Delphi 7 Indy 10, Envia email com  anexos.
// Testado! Funcionando!
//
// E não importa o que eu sofri.O que importa é que eu sobrevivi;
// Sarah Farias. https://www.letras.mus.br/mc-joe/1046127/

procedure TForm1.Button1Click(Sender: TObject);
var
 SMTP:TIdSMTP;
 MSG: TIdMessage;
 SSLSocket:TIdSSLIOHandlerSocketOpenSSL; // <============== ***  indy 10
 attachFiles: TStringList;// <============== *** uses IdAttachmentFile
 i:integer;
begin

   // Criando objetos de conexão
   attachFiles:=TStringList.Create;
   SMTP:= TIdSMTP.Create(nil);
   MSG:= TIdMessage.Create(nil);
   SSLSocket:= TIdSSLIOHandlerSocketOpenSSL.Create(nil); //<==============

   // Formatando objeto de conexão (TIdSMTP)
   with SMTP do
   begin
      AuthType := atDefault;  //  <============== ***
      Host := TextServer.Text; //imap.gmail.com
      IOHandler := SSLSocket;

      Password := TextPassword.Text;// optei por tonar o meu gmail com senha propria para APPs com 16 dígitos.
                                    // Neste caso, o nome do executavel delphi (project1.exe) tem que estar cadastrado no gmail.
                                    // veja https://support.google.com/mail/answer/185833?hl=pt-BR

      Port :=strtoint(Rd_Porta_Gmail.Items[Rd_Porta_Gmail.ItemIndex]);// usei a: 587
      Username := TextUser.Text; //endereço eletronico do remetente não esqueça o @gmail.com!!
      UseTLS:=utUseExplicitTLS;

   end;

   // Formatando objetos de conexão (TIdSSLIOHandlerSocketOpenSSL)
   with SSLSocket do
   begin
      SSLOptions.Method := sslvSSLv23; //  <============== *** 23
      SSLOptions.Mode := sslmClient;
      Destination :=  TextServer.Text+inttostr(SMTP.port);
      Host :=  TextServer.Text;
      Port := SMTP.port;
   end;

   //Buscando Caminhos dos Anexos'

   for i:=1 to ListBox_Envio.items.Count do
      attachFiles.Add(ListBox_Envio.items.Strings[i-1]);

   //Anexando....

   if(Assigned(attachFiles)) then begin
              for i := 1 to attachFiles.Count  do
              begin
                   if FileExists(attachFiles[i-1]) then
                   begin
                        TIdAttachmentFile.Create(msg.MessageParts,attachFiles[i-1]);
                        //showmessage('i='+inttostr(i)+' File Exists('+attachFiles[i-1]+')');
                   end
                   else
                        //showmessage('i='+inttostr(i)+' No Exists File('+attachFiles[i-1]+')');
                end;
            end;

   //showmessage('Anexou');


   // Compondo a mensagem total de envio
   with MSG do
   begin
      msg.ContentType := 'multipart/mixed';
      Body.Add('corpo da mensagem');
      From.Address := Textuser.text; //opcional
      From.Name := 'Nome Remetente'; //opcional
      Recipients.Add;
      Recipients.Items[0].Address := EdtPara.Text;
      Recipients.Items[0].Name := 'Nome Destinatário'; //opcional
      Subject := 'assunto da mensagem';
   end;


   // Efetivando o Envio:
   try
      showmessage('A conectar');
      SMTP.Connect();
      showmessage('Conectou');
      SMTP.Send(MSG);

      showmessage('Enviou');
      SMTP.Disconnect;
   except
      ShowMessage('Falha no envio!');
      exit;
   end;
   ShowMessage('Mensagem enviada com sucesso!');
end;

-1

procedure TForm1.Button3Click(Sender: TObject);
var
 SMTP:TIdSMTP;
 MSG: TIdMessage;
 SSLSocket:TIdSSLIOHandlerSocketOpenSSL;
begin
   SMTP:= TIdSMTP.Create(nil);
   MSG:= TIdMessage.Create(nil);
   SSLSocket:= TIdSSLIOHandlerSocketOpenSSL.Create(nil);

   with SMTP do
   begin
      AuthType := atDefault;//atLogin;//satDefault;//atLogin;atUserPass;
      Host := TextServer.Text;
      IOHandler := SSLSocket;
      Password := TextPassword.Text;
      Port :=strtoint(Rd_Porta_Gmail.Items[Rd_Porta_Gmail.ItemIndex]);
      Username := TextUser.Text; //não esqueça o @gmail.com!!
      UseTLS:=utUseExplicitTLS;//utUseImplicitTLS;
   end;
   with SSLSocket do
   begin
         SSLOptions.VerifyMode := [];
         SSLOptions.VerifyDepth := 0;
       //  OnStatusInfo := IdSSLSocketStatusInfo;
      SSLOptions.Method := sslvSSLv23;
      SSLOptions.Mode := sslmClient;
      Destination :=  TextServer.Text+inttostr(SMTP.port);
      Host :=  TextServer.Text;
      Port := SMTP.port;
   end;

   with MSG do
   begin
      msg.ContentType := 'multipart/mixed';
      Body.Add('corpo da mensagem');
      From.Address := '[email protected]; //opcional
      From.Name := 'Nome Remetente'; //opcional
      Recipients.Add;
      Recipients.Items[0].Address := EdtPara.Text;
      Recipients.Items[0].Name := 'Nome Destinatário'; //opcional
      Subject := 'assunto da mensagem';
   end;
   try
      showmessage('A conectar');

      SMTP.Connect();

      showmessage('Conectou');

      SMTP.Send(MSG);

      showmessage('Enviou');

      SMTP.Disconnect;

   except

      ShowMessage('Falha no envio!');

      exit;

   end;

   ShowMessage('Mensagem enviada com sucesso!');

end;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.