How to login to a Gmail account and get number of messages in a mailbox with TIdIMAP4?

别说谁变了你拦得住时间么 提交于 2019-11-30 07:23:29

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!