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