It was narrated from Abu Hurayrah (may Allaah be pleased with him) that
The Prophet (peace and blessings of Allaah be upon him) said:
“Allaah has forgiven my ummah for whatever crosses their mind so long as they do not speak of it or act upon it.” Narrated by al-Bukhaari (2528) and Muslim (127).
Al-Nawawi (may Allaah have mercy on him) said commenting on this hadeeth:
Whatever crosses a person’s mind, so long as he does not dwell on it or continue to think of it, he is forgiven for it, according to scholarly consensus, because it does not happen voluntarily and he has no way of avoiding it.
Al-Adhkaar (p. 345).