Advanced and durable foams are used extensively in car manufacturing to control sound and vibration in a vehicle, in addition to stiffening body panels and allowing bumpers to be much lighter and safer than they were in the past. However, these are not the same foams as the expandable spray products you can find in home repair and auto parts stores. This kind of expandable foam shouldn't be used to patch rusty areas or other DIY auto body repairs for the following four reasons.
First, most of the expanding foam products available for DIY use create an open cell structure, once they're expanded and cured. These open cells are like tunnels that can let moisture travel into the middle of the foam. While a chunk of uncovered open cell foam can release this moisture, it doesn't have a chance to evaporate when the foam is trapped inside a body panel under layers of auto paint. Trapped moisture leads to more rust and serious structural problems that can make a car dangerous to drive.
Body panels made of metal are designed through extensive testing to verify they're safe in case of a collision. When pinholes of rust damage a panel, and you attempt to fill and cover them with foam, you're doing nothing to reinforce the reduced strength of the panel. This is especially dangerous in impact zones, like the quarter panels and bumpers. Even areas that were filled with foam at the factory shouldn't be repaired with a DIY product that doesn't offer the same exact amount of shock absorption or impact resistance.
There are dozens of different lead and plastic-based body filler products used for smoothing out depressions and small holes in body panels. These products are all designed with smoothing ability in mind, so the body repair technician can make the repair disappear with some sanding and polishing. Foam simply never smooths out as well as a stiffer and stronger filler product, leaving exposed areas rougher and visibly patched to the naked eye.
Finally, adding foam to an area that was never filled with it before can change how the car reacts during a collision. Making even a small change in the density or ability to bend of a certain part of a car can cause deadly results in a serious accident. Repairs completed by a licensed shop are handled in ways approved by the manufacturers, to retain the same safety features of the vehicle as it was originally designed.