-2

Im trying to send mail using this code:

With IdMessage1 Do Begin
  Recipients.EMailAddresses := 'XXXXX@gmail.com';
  From.Address              := 'XXXXX@gmail.com';
  From.Name                 := edit_from.Text;
  CCList.EMailAddresses     := '';
  BccList.EMailAddresses    := '';
  Priority                  := mpNormal;
  Subject                   := edit_subject.Text;
  Body.Add(memo_body.Lines.Text);
End;

With IdSMTP1 Do Begin
  Host      := 'smtp.gmail.com';
  Username  := 'XXXXX@gmail.com';
  Password  := '*****';
  IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(Self);
  Port      := 465;
  UseTLS    := utUseImplicitTLS;

  Try
    Connect;
  Except
  End;

  If Not Connected Then Begin
    Showmessage('Error');
    Exit;
  End;

  Try
    Send(IdMessage1);
  Finally
    Disconnect;
  End;
End;

It works fine on my computer but when i test it on other machines the 'ERROR' (Error in If block before last Try block) will be raised... Where is the problem?

Armin Taghavizad
  • 1,625
  • 7
  • 35
  • 57

1 Answers1

1

This is not the proper way to do error handling with Indy. It should be more like this instead:

With IdSMTP1 Do Begin
  IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(Self);
  UseTLS    := utUseImplicitTLS;
  Host      := 'smtp.gmail.com';
  Username  := 'XXXXX@gmail.com';
  Password  := '*****';
  Port      := 465;

  Try
    Connect;
    Try
      Send(IdMessage1);
    Finally
      Disconnect;
    End;
  Except
    Showmessage('Error');
    Exit;
  End;
End;

Send() and Disconnect() can fail just as easily as Connect() can. If you want Connect() to be in its own try/except block, then at least don't use Connected to validate whether Connect() succeeded:

Try
  Connect;
Except
  Showmessage('Error connecting');
  Exit;
End;

Try
  Try
    Send(IdMessage1);
  Finally
    Disconnect;
  End;
Except
  Showmessage('Error sending');
  Exit;
End;

That being said, the exception tells you what actually failed, so do not ignore it. Had you displayed its content, you would have had a better idea of what was failing, eg:

Except
  on E: Exception do
  Begin
    ShowMessage(Format('Error!'#10'[%s] %s', [E.ClassName, e.Message]));
    Exit;
  End;
End;

The most likely culprit is that you did not deploy the OpenSSL DLLs with your app. You can download them from OpenSSL's website, or from Indy's Fulgan mirror.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • I used the exception and what i received was "Socket Error #11001 - Host not Found" – Armin Taghavizad Oct 14 '14 at 14:36
  • Then your machine's DNS subsystem is having trouble resolving smtp.gmail.com to an IP address. That is outside of Indy. Indy itself works fine with GMail when it is able to connect. – Remy Lebeau Oct 14 '14 at 16:04