I haven't used it, but it sounds like the zlib plugin would do what you want: https://doc.dovecot.org/configuration_manual/zlib_plugin/