What should I do when my accepted paper is subsequently rejected?
Check with the journal. Especially do this if the rejection email you received looks like an auto-generated email. No rational journal would act in such a way, so my gut feeling says there was a mistake somewhere, most likely human error. It is possible that, e.g., the final status of your manuscript was accidentally set to 'reject' instead of 'accept'.