What should I do when my accepted paper is subsequently rejected? My paper was accepted for publication in a journal. I have also received an acceptance letter and even I have filled out the copyright form. The corresponding editor first told me "Your paper is published in one of the volumes of 2017" and next time said that my paper is "published in 2018", but now I have received an email that my paper is "rejected because the paper is not in the aim and scope of the journal"!!!

Really I do not know, what should I do?
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'.