The network of the national railway of Morocco was renovated the past years and several high-speed-connections will follow.
The main routes are from Oujda via Fes, Meknes to Rabat. And from Tangier to Rabat. Then from Rabat to the South in directions of Casablanca, El Jadida, Qued Zem, Marrakesh and Agadir.
To travel by train and ferry from Morocco to Spain, first travel by train to Tanger-Ville, the main station of Tanger. There you change to the hourly (06:00 to 22:00 h), free (if you show your ferry ticket) bus to the harbour Tanger-Med.
In Tanger-Med you change to the ferry in direction of Algeciras (Spain): several providers are available with frequent connections. The journey time is about 1:30h.
In Algeciras (Spain), change back to a train to your destination in Spain.