SendEmail with Indy components

前端 未结 2 450
借酒劲吻你
借酒劲吻你 2020-12-18 02:59

I try to send an email, but I have a problem, however, I found this code on the web:

Uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls,         


        
相关标签:
2条回答
  • 2020-12-18 03:45

    For google smtp you need to use TLS or SSL! http://support.google.com/mail/bin/answer.py?hl=en&answer=13287

    Your procedure sample is write for INDY9 and if you use INDY10 can't compile. You need to make adjustements.

    0 讨论(0)
  • 2020-12-18 03:57

    The code from your question is written for Indy 9 and from your compiler error seems you're using Indy 10. To your compiler errors:

    • Undeclared identifier: Self - the Self is the pointer to the class instance itself and since you didn't write the SendSimpleMail as a class method but just as a standalone procedure, you don't have any Self just because you don't have any class. The class method you could write for instance for your form class like e.g. TForm1.SendSimpleMail, where inside of that method the Self would have meaning of the TForm1 instance, the form itself.

    • And the rest of the errors you got because you were accessing the TIdSMTP class, not the object instance. Commonly used practice is to declare a local variable, create an object instance assigning it to that variable, work with that object (variable) and free the object instance.

    I would try something like this (tested with Indy 10 shipped with Delphi 2009):

    uses
      IdSMTP, IdMessage, IdEMailAddress;
    
    procedure SendSimpleMail;
    var
      IdSMTP: TIdSMTP;
      IdMessage: TIdMessage;
      IdEmailAddressItem: TIdEmailAddressItem;
    begin
      IdSMTP := TIdSMTP.Create(nil);
      try
        IdSMTP.Host := 'smtp.gmail.com';
        IdSMTP.Port := 25;
        IdSMTP.AuthType := satDefault;
        IdSMTP.Username := 'username@gmail.com';
        IdSMTP.Password := 'password';
        IdSMTP.Connect;
        if IdSMTP.Authenticate then
        begin
          IdMessage := TIdMessage.Create(nil);
          try
            IdMessage.From.Name := 'User Name';
            IdMessage.From.Address := 'username@gmail.com';
            IdMessage.Subject := 'E-mail subject';
            IdMessage.Body.Add('E-mail body.');
    
            IdEmailAddressItem := IdMessage.Recipients.Add;
            IdEmailAddressItem.Address := 'recipient@email.com';
    
            IdSMTP.Send(IdMessage);
          finally
            IdMessage.Free;
          end;
        end;
        IdSMTP.Disconnect;
      finally
        IdSMTP.Free;
      end;
    end;
    
    0 讨论(0)
提交回复
热议问题