well, it works but this might not be very efficient if you have a lot of entries.
I mean you're reading the whole directory then "grep"...
You have to know that such LDAP search is not very fast (although you might not be concerned with performance) but it also consumes resources server side.
The proper way, from ldap standpoint, is to use ldapsearch command. Furthermore, it will give you more flexibility to refine entries you want to take in account. (e.g. you may have entries with mail attribute that you don't want to keep in your list)
if goal is to search for all entries with mail address, then your ldap search filter would be:
(mail=*)
if goal is to tackle only users and groups, you may use
(&(mail=*)(|(objectclass=couriermailaccount)(objectclass=couriermailalias)))
notice that if searching for users only, you can refine your ldap search base to ou=users,dc=...
while if searching for groups too (in fact aliases), search base must cover both thus dc=...
You can store result in LDIF file of course.
One last comment: be sure that mail attribute is indexed. I don't know the current status but some time ago, default Zentyal deployment was not maintaining such index