To re post an old post of mine:
All sorts of thoughts can happen to us out of the blue…
(not sought…they just happen…one does not want them…they may even be rather annoying…)
Be they impure etc etc
The fact that a thought happened to one- does not mean per se there was any sin.
And for mortal sin one needs not only grave matter, full knowledge and deliberate (complete) consent…
Just cause a thought happened to you does not mean there was any sin. Let alone mortal sin.
Just calmly turn to something good…
For the next few moments --try real hard NOT to think of an Apple.
then scroll down.
What did you think of?
Even though your will was against it (you did not want to think of an apple!)
Now back to unwanted thoughts…
The more you fear and try hard not to have them…the more they will likely come and bother you.
The best thing to do with such thoughts is not to fight them directly --not fear that they will come—simply do not consent and simply and calmly turn to something else…(or it may be best to keep doing the good thing one is doing…like they come out of the blue when your at work …keep working…keep praying …etc)
It is an age old trouble that can happen - as one can find in spiritual works down through the ages.
There is a story from the desert of the early Centuries of the Church where a younger hermit when to an older one with the problems of thoughts happening to him all the time…the older hermit told him to go outside open his cloak and catch the wind.
The younger hermit said such is not possible…
the older hermit replied --neither is it possible to stop all the thoughts that can come to you…(then basically he said his task was not to consent…if they should happen…hence I would add one would turn to something else that is good…).
Ignore such unwanted thoughts like one would ignore a hissing goose or a barking dog. One does not stop to argue with a hissing goose or a barking dog does one? No one keeps on walking…
(as noted above the image there comes from a Carthusian Monk from centuries ago…)
Bottom line: Ignore such unwanted thoughts and do not fear them…just calmly turn to something good.