How should I apply spray foam around a ceiling mounted bathroom exhaust vent?
Rather than using that spray foam you'd be better off getting a sheet of Styrofoam and cutting it to fit the opening around your fan. Make a template out of cardboard and then trace it on to the Styrofoam, cut it out and fit it into the opening. You can then caulk around it sealing it further.
Now, you need to make that direct connection to the duck you said was already in the attic. You're looking for trouble venting hot, moist air directly into your attic/crawlspace.