@bkm Actually what I did to get around the custom port issue was to add port redirection to erpnext machine.
To do that (on Debian Linux) add /etc/init.d/redir.imap (chmod 0755, change redir.imap as you see fit) script:
(replace uppercase terms with suitable values)
#! /bin/sh
# /etc/init.d/redir.imap
# The following part always gets executed.
echo "Redirect local port 993 to IMAP_SERVER_ADDRESS:CUSTOM_PORT"
redir --lport=993 --laddr=127.0.0.1 --cport=CUSTOM_PORT --caddr=IMAP_SERVER_IP_ADDRESS &
Afterwards setup erpnext for imap to be directed to localhost.
Also change 993 to whichever port erpnext expects.