It's not an appropriate tool.
Openssl is not an IMAP client. It is able to encapsulate plain text communication in a TLS/SSL tunnel - exactly the kind of encryption around IMAP that happens in IMAPs. So, that article is basically an article that describes how to manually type in IMAP commands using telnet, just that you replace telnet with a cryptographically secure alternative. You're not a command typing machine. Leave that up to a library that knows how to speak IMAP correctly.
You want an IMAP client. CURL could actually download message parts, so, do what you try to do here. So does fetchmail. There's actually quite a few IMAP clients out there - probably also for the scripting language of your choice! I'd strongly recommend you don't use your shell but a properer scripting language, as you really don't want to re-establish a connection to the server for every single email. As a matter of fact, my mail servers would block you after the first couple dozen connection requests in less than a minute.
However, what you do makes little sense in achieving what you want. You should instead ask the server to search on your behalf on the server itself, not try to download all message headers and look for matches in them. IMAP clients tend to offer access to the search protocol that IMAP offers. So go that route.