The accused, mostly from impoverished Sudan, were arrested on June 23 during a Moroccan operation near Melilla, which along with Spain's other enclave of Ceuta is the EU's only land border with Africa.
The 14 were charged with offenses including belonging to a criminal immigration gang and insulting law enforcement officers, Bouirig said.
Omar Naji of the AMDH human rights group, which monitored the trial, said the migrants did not try to cross the border.
"Why condemn migrants whose sole wrongdoing was to have taken refuge in a forest?" he asked.
"It's a very severe judgement," the defendants' lawyer, Mbarek Bouirig, told AFP.
He said he planned to appeal
At least 23 migrants died the following day when around 2,000 people, many also Sudanese, stormed the fences along the frontier. It was the heaviest death toll in years of attempted crossings into the enclaves.
Spanish rights group Caminando Fronteras says as many as 37 people lost their lives in the mass crossing attempt, higher than the official toll of 23.
A Moroccan court last month sentenced 33 migrants to 11 months in jail for illegal entry, while a separate trial of 29 migrants including a minor continues.
The United Nations, the African Union and independent rights groups have condemned the use of excessive force by Moroccan and Spanish security personnel.