Searching Email Messages

This section describes how to search for a given string in the email messages.

Perform the steps described in Listing, Accessing and Launching Mailboxes.

Email Client provides MEmailSearchObserver class for handling email search results and MEmailMessageSearchAsync class for initiating the asynchronous search.

For a specific mailbox, the search function searches for a given string in all the fields of the messages.

The search client is notified of each found message and the MEmailSearchObserver::SearchCompletedL() method notifies when the search is completed.

Note: Only one search can be performed at a time. If a search is already in progress, returns KErrNotReady.
  1. Implement the MEmailSearchObserver class and initiate the search using MEmailMailbox::MessageSearchL().
    MEmailMailbox* mailbox = mailboxes[i];
    MEmailMessageSearchAsync* search = mailbox->MessageSearchL();
    CleanupReleasePushL( *search );
    search->StartSearchL( *this ); // this implements MEmailSearchObserver
    
  2. To cancel the search use MEmailMessageSearchAsync::Cancel() method.

The following code snippet shows an example of how to search for a given string on all the mailboxes that are found.

TInt CEmailClientApiTester::SearchWithResultsL( CItemParser& /* aItem */)
	{
		TInt ret(KErrNone);    
		MEmailClientApi* mailClient = CreateFactoryAndClientApiLC();  // Factory, client
		RMailboxPtrArray mailboxes;   
		CleanupResetAndRelease<MEmailMailbox>::PushL( mailboxes );    // Mailboxes
		mailClient->GetMailboxesL( mailboxes );
		if (mailboxes.Count() > 0)
		{
			MEmailMailbox* mailbox = mailboxes[0]; // Do the test with the first found mailbox
			MEmailMessageSearchAsync* searchAPI;            
			searchAPI = mailbox->MessageSearchL();
			searchAPI->AddSearchKeyL(_L("Test1"));
			searchAPI->AddSearchKeyL(_L("Test2"));        
			TEmailSortCriteria criteria;
			criteria.iAscending = ETrue;
			criteria.iField = TEmailSortCriteria::EByDate;                 
			searchAPI->SetSortCriteriaL(criteria);
			CSearchObserver* obs = CSearchObserver::NewL(this);
			CleanupStack::PushL( obs );        
			searchAPI->StartSearchL(*obs);
			TInt status = searchAPI->Status();
			iLog->Log( _L( "Search started, ascending=true, status=%d"), status);
			obs->Wait();
			searchAPI->Reset();
			searchAPI->AddSearchKeyL(_L("Test1"));
			searchAPI->AddSearchKeyL(_L("Test2"));        
			criteria.iAscending = EFalse;
			criteria.iField = TEmailSortCriteria::EByDate;                 
			searchAPI->SetSortCriteriaL(criteria);
			searchAPI->StartSearchL(*obs);
			status = searchAPI->Status();
			obs->Wait();
			searchAPI->Release();        
		}
		else
		{
			ret = KErrNotFound;        
		}
		CleanupStack::PopAndDestroy(4); // factory, mailClient, mailboxes, observer return ret;
	}
Related concepts
Email Client API Overview