I have these values to connect to an IMAP sever:

hostname
username
password

I want to auto-detect the details with Python:

port
ssl or starttls

If the port is one of the well-known port numbers there should be not too many possible combinations. 
Trying all would be a solution, but maybe there is a better way?
You pretty much have to brute force it, but there's really only three setups, and it only requires two connects:

First connect on port 993 with regular SSL/TLS.    If this works: 993/TLS. If this fails:
Connect to port 143, and check if CAPABILITY STARTTLS exists.  If it does: try StartTLS.  If this works:   143/STARTTLS.  Else:
See if you can log in on port 143.  if this fails, no good configuration.  This wouldn't be secure anyway, so should be discouraged.

SMTP is a bit more complex:  You can try 587 with StartTLS, 465 with TLS, or 25 with StartTLS, plain, or no authentication at all.
Note: autodetecting STARTTLS is dangerous, as it allows a MITM attack, where the attacker hides the STARTTLS capability so that you attempt to login without it.  You may want to ask the user if they wish to connect insecurely, or provide a 'disable security' setting that must be opted into.
Autodetect IMAP connection details