iCloud IMAP has some quirks. A few things to double-check:
Use an App-Specific Password — this is required since Apple enables 2FA by default. Generate one at appleid.apple.com under Security > App-Specific Passwords.
Use the correct server settings:
IMAP server: imap.mail.me.com, port 993, SSL
SMTP server: smtp.mail.me.com, port 587, STARTTLS
Username must be your full @icloud.com address (or @me.com/@mac.com), not just the part before the @.
Make sure IMAP is enabled in iCloud settings — go to iCloud.com > Mail > Settings gear icon > Preferences > IMAP, and ensure it’s turned on.
If you’re still seeing AUTHENTICATIONFAILED after checking all of the above, try generating a fresh app-specific password — they occasionally need to be regenerated.