This seems to be a certificate issue.
I don't tell you what the certificate issue is nor how to solve it.
However, you can leave your gmail account open to attacks by ignoring that issue disabling the certificate validation:
$hostname = '{imap.gmail.com:993/ssl/novalidate-cert}[Gmail]/All Mail';