Referred candidates and internal applicants both require more care than external applicants you haven't met. For a referred candidate, the rejection touches two relationships: the candidate's and the employee who made the introduction. A brief rejection from the hiring manager, not an ATS form email, is appropriate. Let the referring employee know the outcome directly before the candidate hears it. "We've reached out to [Candidate] to let them know we're going another direction. We really appreciated you thinking of us" keeps the referring employee in the loop.
Internal rejections are more sensitive still. The person will remain a colleague and will know who was hired instead. Keep the email honest, acknowledge their initiative in applying, and when you can, give one constructive piece of context. Not a full debrief, but enough that the rejection doesn't feel arbitrary. "We went with someone who had more direct experience in [area], but your interest in this kind of work is noted and I'd like to talk about how to get there" is far better than a form decline. When it makes sense, follow the email with a short conversation.