How to login to a Gmail account and get number of

2019-02-05 03:30发布

问题:

How can I login to a Gmail account and get number of messages in the INBOX mailbox with TIdIMAP4 component ?

回答1:

To get the total number of messages in your Gmail's inbox, you need to, first connect to the Gmail IMAP server with your credentials, select Gmail's inbox mailbox and for that selected mailbox read the value of the TotalMsgs property.

In code it may looks like follows (this code requires OpenSSL, so don't forget to put the libeay32.dll and ssleay32.dll libraries to a path visible to your project; you can download OpenSSL libraries for Indy in different versions and platforms from here):

uses
  IdIMAP4, IdSSLOpenSSL, IdExplicitTLSClientServerBase;

function GetGmailMessageCount(const UserName, Password: string): Integer;
var
  IMAPClient: TIdIMAP4;
  OpenSSLHandler: TIdSSLIOHandlerSocketOpenSSL;
begin
  Result := 0;
  IMAPClient := TIdIMAP4.Create(nil);
  try
    OpenSSLHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
    try
      OpenSSLHandler.SSLOptions.Method := sslvSSLv3;
      IMAPClient.IOHandler := OpenSSLHandler;
      IMAPClient.Host := 'imap.gmail.com';
      IMAPClient.Port := 993;
      IMAPClient.UseTLS := utUseImplicitTLS;
      IMAPClient.Username := UserName;
      IMAPClient.Password := Password;
      IMAPClient.Connect;
      try
        if IMAPClient.SelectMailBox('INBOX') then
          Result := IMAPClient.MailBox.TotalMsgs;
      finally
        IMAPClient.Disconnect;
      end;
    finally
      OpenSSLHandler.Free;
    end;
  finally
    IMAPClient.Free;
  end;
end;

procedure TForm1.ConnectButtonClick(Sender: TObject);
begin
  ShowMessage('Total count of messages in inbox: ' +
    IntToStr(GetGmailMessageCount('UserName@gmail.com', 'Password')));
end;

You may optionally download a demo project which includes OpenSSL v1.0.1c libraries for i386 platform for 32-bit applications (compiled in Delphi 2009).