The hosts found themselves up against it in the 16th minute when Jose Willian was shown a straight red card by the referee, forcing Castilla to play the remaining 74 minutes a man down.
However, they managed to take the lead shortly before the hour mark as Lucas Vazquez fired an effort past the keeper to break the deadlock.
Mallorca eventually made their man advantage pay with just six minutes of the match remaining as Tomer Hemed levelled things up for the visitors.
The comeback was completed four minutes later when Thomas Teye broke Castilla hearts with an 88th-minute strike that gave his side a dramatic late victory.
The hosts could have rescued a point in second-half stoppage time as they were awarded a penalty, but Omar Mascarell squandered the opportunity and missed his spot kick.