Connecting to gmail is tricky as google tries to discourage people from using other mail clients than web browsers. First you need to visit google account and check the setting that allows "apps & devices to access your account in a less secure way". Google then will frequently spam your mailbox asking to uncheck this.
Now, to the point.
To access gmail via imap (google discourages pop protocol and so do I) you need to use 993 port and add control line feed to openssl option. Spam folder is [Gmail]/Spam and, as I understood, you want to get its next unique ID, so the typical session should look like this:
$ openssl s_client -connect imap.gmail.com:993 -crlf
CONNECTED(00000003)
depth=2 OU = GlobalSign Root CA - R2, O = GlobalSign, CN = GlobalSign
verify return:1
depth=1 C = US, O = Google Trust Services, CN = Google Internet Authority G3
verify return:1
depth=0 C = US, ST = California, L = Mountain View, O = Google LLC, CN = imap.gmail.com
verify return:1
---
[...]
---
* OK Gimap ready for requests from 10.0.0.1 n9mb133f65154lxl
a1 LOGIN <user> <password>
* CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 UIDPLUS COMPRESS=DEFLATE ENABLE MOVE CONDSTORE ESEARCH UTF8=ACCEPT LIST-EXTENDED LIST-STATUS LITERAL- SPECIAL-USE APPENDLIMIT=35651584
a1 OK [email protected] authenticated (Success)
a2 STATUS "[Gmail]/Spam" (UIDNEXT)
* STATUS "[Gmail]/Spam" (UIDNEXT 2127)
a2 OK Success
a3 LOGOUT
* BYE LOGOUT Requested
a3 OK 73 good day (Success)
read:errno=0
The commands actually typed by you are those started with tags aN. Tags are obligatory by imap protocol, so don't forget about them; they don't need to be in aN form, any string is fine. Obviously change <user> and <password> to yours.