Foxes spray for several reasons:
Marking Territory
Foxes have scent glands near their tails that secrete a strong-smelling musk. This deters other foxes from entering their territory and helps attract mates.
Communication
Spraying lets other foxes know they are in the area or warns them of danger, such as the presence of a predator.
Defense
If threatened, a fox may spray an attacker in the face or eyes to deter them and escape.