For something like this, I think that it's better to do it in person if you can. Because when it comes to stuff like this, the best way to comfort someone is to simply hear what they have to say and allow them to be vulnerable with you. Make them feel that you can be trusted and that you won't judge them for anything.
I know from personal experience that if you always did well on tests and things like that and then have one failure, it's as if you let the whole world down. You let yourself down, you let your family down, you let your friends down, and you don't know what you're supposed to do. That's why as a friend, you shouldn't tell him that he needs to go out there and be a man and do better next time. They may seem encouraging but that almost never works. What you need to do is allow him to feel terrible, to let him know that what he feels is perfectly okay, and to assure him that you aren't going to leave him or think of him worse just because of this. Before you can encourage him to do better, he needs to accept this failure first. It may take a few hours or it may take months! Whatever that may be, you have to be as patient as you can with him and allow him to grow from this experience without confusing him with "encouraging statements".
Once he learns to accept this failure, then the next step is to tell him that you believe in him in doing better. Tell him why you value him and what makes you think that he can do better. You can also tell him about how there are other people out there who have failed examinations and felt discourage but they were able to make it through. But with that one I'd be careful how you phrase it because one wrong word could make it sound like you're nagging him for not being strong enough and the strength that he managed to muster could all fall into pieces.
But if you live long distance, then it's probably better to email him or call him or whatever so you'll have more immediate interactions. Although if possible, please try to talk to him in person.