It is narrated from Sayyiduna Abu Hurayrah (may Allah be pleased with him) that the Prophet (peace and blessings be upon him) said: "A man said: I will give charity tonight. He went out with his charity and (unknowingly) gave it to an adulteress. In the morning people began saying that charity was now being given even to an adulteress. He said: 'Allahumma laka al-hamd' (O Allah, to You alone belongs all praise), charity to an adulteress? The next night he went out again with charity and gave it to a wealthy man. In the morning people again began saying that charity was being given even to the rich. He again said: 'Allahumma laka al-hamd' (O Allah, to You alone belongs all praise), what is happening to me? On the third night he went out again with charity and placed it in the hand of a thief. In the morning people again said that charity had been given to a thief during the night. He said: 'Allahumma laka al-hamd' (O Allah, to You alone belongs all praise), first to an adulteress, then to a rich man, and then to a thief I have given my charity. Then he was told: Your charity has been accepted. As for the adulteress, perhaps she will refrain from adultery; as for the wealthy man, perhaps he will take a lesson and begin giving charity; and perhaps the thief will take a lesson from it and refrain from stealing."
Hadith Referenceالسنن الكبرى للبيهقي / كتاب قسم الصدقات / 13252