Reading IMAP emails via PHP

Actually, this is not complicated, but it has a rather large list of what it might be needed for.
I personally used it to send to myself in VK notifications about the release of new episodes of my favorite series. These notifications just come to one of my mailboxes.
I already mentioned how to write messages in VK through PHP in one of the previous entries, VK bot and callback api

Here I will only talk about IMAP.

Connecting to IMAP via PHP is as follows:

$host = '{HOST.RU}';
$email = 'EMAIL@HOST.RU';
$pass = 'PASSWORD';
    $connect = imap_open($host, $email, $pass)
        or die("can't connect: ".imap_last_error());

You can also add all sorts of different options to the host. The port is most often used 993, so I'll set it up right away.
{HOST.RU:993/ssl/novalidate-cert}INBOX

The ssl setting indicates that You need to use SSL for encryption.
The novalidate-cert option indicates that the certificate should not be checked. If you have a self-signed certificate on the server, that's what you need!
More parameters you can find in the official documentation, let's not focus on this.

By the way, until I used SSL with novalidate-cert, I got this error.

can't connect:[CLOSED] IMAP connection broken (server response)

Let's get all the unread emails in the drawer and put them on the screen.

	$new_mails = imap_search($connect, 'UNSEEN'); //Get the ID of unread messages
	$new_mails = implode(",", $new_mails); //Let's collect all IDs in a comma separated line

	$overview = imap_fetch_overview($connect,$new_mails,0); //Get info from message headers
	
	foreach ($overview as $ow) { //run through the resulting array. Each element of the array is a new letter.
		$subject = iconv_mime_decode($ow->subject,0,"UTF-8"); //We get the subject of the letter and immediately decode it
		//because most likely the topic will not have human readable encodings
		
		$body = imap_fetchbody($connect,$ow->msgno,1); //We get the contents of the letter. He will likely already have
		//need the encoding. Therefore, we leave it this way. If not, then you know what to do, ahah.
		//After performing this function, the letter will be automatically read.
		
		echo "Subject: $subject <br />"; //We derive the subject of the letter
		echo "Body: $body <br /><br />"; //Print the contents of the letter
	}
	
	imap_close($connect); //Do not forget to close the connection

That's all. It's not complicated. If there are any questions - ask them in the comments. )