The Messenger of Allah ﷺ said, "A man once said, 'Tonight I shall give a charity.' So he took out his charity and placed it in the hand of an adulteress. The next morning the people were talking, saying, 'Charity was given last night to an adulteress.'He said, 'Tonight I shall give a charity.' So he took out his charity and placed it in the hand of a thief. The next morning the people were talking, saying, 'Charity was given last night to a thief.'He said, 'Tonight I shall give a charity.' So he took out his charity and placed it in the hand of a rich man. The next morning the people were talking, saying, 'Charity was given last night to a rich man.'He said, 'All praise is due to Allah, even for charity given to a thief, an adulteress, and a rich man.'Then he was visited and told, 'As for your charity, it has been accepted. As for the adulteress, perhaps she will refrain from her sin because of it. As for the thief, perhaps he will refrain from his theft because of it. And as for the rich man, perhaps he will take heed and spend from what Allah has given him.'"
حدثنا علي بن حفص أخبرنا ورقاء عن أبي الزناد عن الأعرج
قال رسول الله ﷺ قال رجل لأتصدقن الليلة صدقة فأخرج صدقته فوضعها في يد زانية فأصبحوا يتحدثون تصدق الليلة على زانية وقال لأتصدقن الليلة بصدقة فأخرج صدقته فوضعها في يد سارق فأصبحوا يتحدثون تصدق الليلة على سارق ثم قال لأتصدقن الليلة بصدقة فأخرج الصدقة فوضعها في يد غني فأصبحوا يتحدثون تصدق الليلة على غني فقال الحمد لله على سارق وعلى زانية وعلى غني قال فأتي فقيل له أما صدقتك فقد تقبلت أما الزانية فلعلها يعني أن تستعف به وأما السارق فلعله أن يستغني به وأما الغني فلعله أن يعتبر فينفق مما آتاه الله
Muslim narrated it in the chapter on zakat, from Suwayd bin Saeed.This hadith establishes that reward is granted for charity even if the recipient turns out to be sinful or wealthy, for in every parched liver there is a reward. This applies to voluntary charity, but as for zakat, giving it to a wealthy person does not fulfill the obligation.In the version of Tabarani, it says that this troubled him, so he was approached in his sleep. Abu Naeem and Ismaili also narrated it this way, and it identifies one of the possibilities, that it was through a vision in a dream, or a voice, or a knowledgeable person.