Is the sin of the same magnitude if done when in need of friendly company which only the other person can provide?
It is haraam for a man to take women as friends. See question no. 1114.
A person should be wise, because whoever says that a man may kiss his female friend on the face in a friendly manner and hug her in a friendly manner is saying something that is regarded as foolish and stupid. It is obvious to any wise person than this kind of behaviour provokes desire, and this is the path that leads to zina (fornication, adultery). It cannot be said that his intention is pure, because Allaah has created men with an inclination to be attracted towards women. Hence Allaah has forbidden men to look at women and has commanded them to lower their gaze. Allaah says (interpretation of the meaning):
“Tell the believing men to lower their gaze (from looking at forbidden things), and protect their private parts (from illegal sexual acts)”
The Prophet (peace and blessings of Allaah be upon him) said: “The eye may commit zina, and its zina is looking.” (Narrated by Abu Dawood, al-Nikaah, 1840; classed as saheeh by al-Albaani in Saheeh Sunan Abi Dawood, no. 1884).
Hence it is haraam to mix with women or to be alone with a woman, even if she is wearing hijaab, so how about if the woman is making a wanton display of herself? There are very many aayahs and ahaadeeth which forbid that. It is also forbidden to shake hands with women; see question no. 2459. A person who allows himself to do these things may start to commit zina zina with her on the grounds of friendship. It cannot be said that this is because of difficult circumstances where he needs a person to stand by him and be his friend. All of that is haraam and is not allowed. Whoever falls into such things must hasten to repent sincerely from this sin, and turn back to Allaah and regret what he has done. The Muslim must realize that if he turns to Allaah for help with the calamities and problems that befall him in this world, Allaah will relieve him of his trouble and grant him relief and a way out, so he should fear Allaah. Allaah says (interpretation of the meaning):
“And whosoever fears Allaah and keeps his duty to Him, He will make a way for him to get out (from every difficulty)”
“and whosoever fears Allaah and keeps his duty to Him, He will make his matter easy for him”
And Allaah knows best.