I found this problem recently and posted on it, so it has existed at least since build 9518, and the problem makes sense.
The API is how webmail is implemented, so an API connection is indistinguishable from a Webmail connection, other than possibly the user agent string. This means that you cannot get around 2FA using one of the application passwords provided for MAPI/IMAP/POP/etc.
The workaround is to configure an account with IP restrictions but not 2FA, and use that account for your API calls. When the script needs a different user context, use impersonation rather than changing logins.
Based on another recent post, you can avoid some impersonation by using a system admin auth token and adding x-smartermail-domain="domain name" to your request header.