I have been looking into this. There is mbsync (isync)[1] which will let you download a imap account. There is also a premade docker image[2] which you could trigger via cron and sync your mails. For gmail it is recommended to get a login token but I have not looked into how to do that.
No API but you could script the browser. Obviously would break if the UI changes. Quick google shows some potentially still-relevant posts: https://superuser.com/q/716756