The siege of a Kabul guesthouse used by a US-based aid group ended after Afghan security forces killed the last Taliban gunman holed up inside, a military commander said.
A teenage girl who worked in the guesthouse was among the dead, he added.
"The fight is over. Five attackers are dead," Qadam Shah Shaheem, commander of 111 Military Corps Kabul, told Reuters news agency.
"One detonated his car loaded with explosives, three others detonated explosives attached to their bodies inside the building, and one was shot by security forces. All four foreigners are alive and safe now."
Several foreigners were evacuated from the guesthouse of Roots of Peace, which works to replace minefields with vineyards, in the west of the city, an AFP photographer at the scene said.
It is the fourth significant attack this year in the Afghan capital targeting foreigners or places where foreigners congregate.
The Taliban have vowed a campaign of violence to disrupt the ballot on April 5, urging their fighters to attack polling staff, voters and security forces in the run-up to election day.
Kabul Police chief Mohammad Zaher said when the attack began around 4:00pm (1200 GMT) there were six foreigners inside the building.
Zaher told AFP they were two Americans, a Peruvian, a Malaysian, an Australian and a guard he described as "African".
There was no immediate confirmation of these nationalities.
The Taliban claimed responsibility for the attack, and said the target was a foreign guesthouse they alleged was also used as a church.
Roots of Peace has been working in Afghanistan, one of the world's most heavily-mined countries, since 2003.
They try to clear minefields laid during the Soviet occupation of the 1980s and the civil war of the 1990s and convert the land to agricultural use.
Since 1989, when Soviet forces left Afghanistan, more than 4,000 people have been killed and 17,000 injured by mines, according to an estimate by the UN's Mine Action Coordination Center of Afghanistan.
The assault comes just three days after Taliban fighters stormed an office of the Independent Election Commission in Kabul, killing five people.
Last Thursday four Taliban gunmen smuggled pistols into Kabul's high-security Serena hotel and shot dead nine people including four foreigners.
The victims also included Agence France-Presse journalist Sardar Ahmad, his wife and two of their three children.
Those attacks followed the daylight shooting of a Swedish radio journalist and an assault in January on a Lebanese restaurant that killed 21 people including 13 foreigners.