It is narrated from Sayyiduna Abdullah bin Abbas (may Allah be pleased with them both) that a man from among the Companions of the Messenger of Allah (peace and blessings be upon him) was attracted to a woman. One day he was sitting in the gathering of the Messenger of Allah (peace and blessings be upon him) when he asked his (peace and blessings be upon him) permission for some need, and he (peace and blessings be upon him) gave him permission. He went out on a rainy day and suddenly saw a woman washing clothes at the edge of a pool (stream). When he saw her, he sat with her the way a man sits with his wife; then he moved his private organ, and it turned out to be (limp) like the fringe of a cloth. So he got up regretful, came to the Prophet (peace and blessings be upon him) and told him (peace and blessings be upon him) what had happened. The Prophet (peace and blessings be upon him) said to him: "Pray four rak'ahs." Then Allah Almighty revealed this verse: "And establish prayer at the two ends of the day and in some hours of the night. Indeed, good deeds remove evil deeds. That is a reminder for those who remember."
It has a supporting narration (shahid) in Sahih Muslim, with the like of it, from the hadith of Sayyiduna Ibn Mas'ud (may Allah be pleased with him) through al-Aswad and Alqamah (may Allah have mercy on them both), and from the hadith of Sayyiduna Abu Umamah al-Bahili (may Allah be pleased with him).
Imam al-Daraqutni (may Allah have mercy on him) said: "Ubaydullah bin Musa (may Allah have mercy on him) is alone in narrating this report through Ibn Uyaynah from al-Zuhri."