Catholic encyclopedia: https://www.newadvent.org/cathen/05047b.htm
Distraction (Latin distrahere, to draw away, hence to distract) is here considered in so far as it is wont to happen in time of prayer and in administering the sacraments. It hardly needs to be noted that the idea of mental prayer and mind-wandering are destructive of each other. So far as vocal prayer is concerned, the want of actual interior attention, if voluntary, will take from its perfection and be morally reprehensible. Distractions, however, according to the commonly accepted teaching, do not rob prayer of its essential character.
To be sure one must have had the intention to pray and therefore in the beginning some formal advertence; otherwise a man would not know what he was doing, and his prayer could not be described even as a human act. So long, however, as nothing is done outwardly which would be incompatible with any degree whatever of attention to the function of prayer, the lack of explicit mental application does not, so to speak, invalidate prayer. In other words, it keeps its substantial value as prayer, although, of course, when the dissipation of thought is wilful our addresses to the throne of mercy lose a great deal of efficacy and acceptability.
This doctrine has an application, for example, in the case of those who are bound to recite the canonical Office and who are esteemed to have fulfilled their obligation substantially even though their distractions have been abundant and absorbing. Voluntary distractions, that is the conscious deliberate surrender of the mind to thoughts foreign to prayers, are sinful because of the obvious irreverence for God with Whom at such times are presuming to hold intercourse. The guilt, however, is judged to be venial.
In the administration of the sacraments their validity cannot be assailed merely because the one who confers them fails to, here and now, think of what he is doing. Provided he has the required intention and posits the essentials of the external rite proper to each sacrament, no matter how taken over he may be by outside reflections, his act is distinctly a human one and as such its value cannot be impugned. Such as state of mind, however, when it is wilful, is sinful, but the guilt is not mortal unless one has thereby laid himself open to the danger of making a mistake in what is regarded as essential for the validity of the sacrament in question.