验证电子邮件地址使用delphi XE5

时间:2014-07-09 18:13:29

标签: delphi delphi-xe5

我想知道。是否可以使用delphi验证电子邮件地址。

我找到了一篇关于如何一步一步地做到这一点的文章。但无法通过代码找到方法。

有什么建议吗?

http://www.labnol.org/software/verify-email-address/18220/

更新1:

我刚刚发现了一篇文章,解释了如何做到我想要的。但我无法让代码工作。我一直在Undeclared identifier 'Tmail' at line 28

http://www.emailarchitect.net/easendmail/ex/d/11.aspx

谢谢

1 个答案:

答案 0 :(得分:2)

Delphi附带Indy,这些步骤可以使用Indy的TIdDNSResolverTIdSMTP组件执行,例如:

function VerifyEmail(const email: string): Boolean;
var
  I: Integer;
  domain: string;
begin
  Result := False;

  I := Pos('@', email);
  if I = 0 then Exit;

  domain := Copy(email, I+1, MaxInt);

  IdDNSResolver1.Host := ... Host/IP of DNS server you want to query ...;
  IdDNSResolver1.QueryType := [qtMX];

  try
    IdDNSResolver1.Resolve(domain);
  except
    Exit;
  end;

  for I := 0 to IdDNSResolver1.QueryResult.Count-1 do
  begin
    if IdDNSResolver1.QueryResult[I] is TMXRecord then
    begin
      IdSMTP1.Host := TMXRecord(IdDNSResolver1.QueryResult[I]).ExchangeServer;
      try
        IdSMTP1.Connect;
        try
          IdSMTP1.SendCmd('MAIL FROM:<labnol@labnol.org>', 250);
          IdSMTP1.SendCmd('RCPT TO:<'+email+'>', [250, 251]);
          Result := True;
          Exit;
        finally
          IdSMTP1.Disconnect;
        end;
      except
      end;
    end;
  end;
end;

或者,使用TIdSMTP.Verify()方法,这样您就不必伪造电子邮件,只是为了发现收件人是否被接受,例如:

function VerifyEmail(const email: string): Boolean;
var
  I: Integer;
  user, domain: string;
begin
  Result := False;

  I := Pos('@', email);
  if I = 0 then Exit;

  user := Copy(email, 1, I-1);
  domain := Copy(email, I+1, MaxInt);

  IdDNSResolver1.Host := ... Host/IP of DNS server you want to query ...;
  IdDNSResolver1.QueryType := [qtMX];

  try
    IdDNSResolver1.Resolve(domain);
  except
    Exit;
  end;

  for I := 0 to IdDNSResolver1.QueryResult.Count-1 do
  begin
    if IdDNSResolver1.QueryResult[I] is TMXRecord then
    begin
      IdSMTP1.Host := TMXRecord(IdDNSResolver1.QueryResult[I]).ExchangeServer;
      try
        IdSMTP1.Connect;
        try
          IdSMTP1.Verify(user);
          Result := True;
          Exit;
        finally
          IdSMTP1.Disconnect;
        end;
      except
      end;
    end;
  end;
end;