I found recently that Apple’s Mail.app was behaving erratically: the notification for unread emails wouldn’t disappear, even after reading all emails; junk email was properly marked as such, but refused to go into the spam folder and the rules I had set for certain senders didn’t work.
It all started after I signed up for iCloud to synch all my email accounts. That should have been my first clue to what the problem was, but it took me some time to realize what was going on. It turns out that iCloud is not smart enough (yet?) to realize that some of the synched accounts were already in place locally on my machine. It would then duplicate my locally set accounts with those from iCloud.
The problem went away once I removed those duplicates causing the problem. I still haven’t decided wether I want all my email accounts in the cloud. I don’t need all of them in all of my devices (I don’t really check all my emails on my iPhone, for example.) So, I decided to keep my most used accounts in the cloud and keep the less used ones on the MacBook that I use most frequently.
If you have the same problem, you should check your “Internet Accounts” in System Preferences and remove those you don’t want them there.