This is the 24th day of my participation in the August Text Challenge.More challenges in August

For mail processing, we are more familiar with POP3, SMTP and other protocols, and today we introduce IMAP is actually a very common mail processing protocol. It is similar to POP3 in that it mainly receives and processes mail. However, in contrast to POP3, IMAP’s local operations are directly synchronized to the online mail server. POP3 generally does not synchronize directly, and this is the biggest difference between the two. As for the specific content of these mail agreements, if there are students who do not know much about them, they can refer to the relevant information on the Internet.

Whether it is IMAP or POP3, combined with SMTP, it is very simple to implement the function of a mail client. In this article, we will focus on some simple aspects of the IMAP extension in PHP.

Install the extension

First, install the IMAP extension. –with-imap and –with-imap-ssl can be added directly to configure at compile time. For post-installation, go directly to the imap directory in the ext directory of the source package to go through the normal extension installation steps.

Note, however, that the IMAP extension requires some components to be installed in the operating system environment as well.

yum install -y libc-client-devel libc-client
ln -s /usr/lib64/libc-client.so /usr/lib/libc-client.a
ln -s /usr/lib64/libkrb5.so /usr/lib/libkrb5.so
Copy the code

We need to install libc-client-devel and set up two soft connections. Otherwise, problems may occur when the extension code is installed.

Connect to QQ Mailbox

Next, let’s try to connect QQ mailbox.

$host = "{imap.qq.com:993/imap2/ssl}INBOX";
$username = "xxxx";   // Do not bring @qq.com
$password = "xxxxxx"; // Authorization login code obtained after iMAP is enabled

$mbox = imap_open($host.$username.$password);
Copy the code

A very simple function, imap_open(), to open a handle to the connection mailbox. The three parameters are also straightforward: host specifies the domain address of the mailbox, and you can directly specify which folder in the mailbox to connect to. Here we go straight to the inbox. When connecting QQ mailbox, the user name can be directly used QQ number, there is no need to put @qq.com in the back. The password is the authorized login code obtained after we select account management in the Settings of QQ mailbox and open the IMAP function.

Checking Email Information

Once you connect to the mailbox successfully, you can view some information about it.

$rowsCount = imap_num_msg($mbox);
echo $rowsCount, PHP_EOL;
/ / 37
Copy the code

Imap_num_msg () returns the number of messages in the mailbox, which is actually the number of our messages.

$list = imap_list($mbox."{imap.qq.com}"."*");
var_dump($list);
// array(6) {
/ / [0] = >
// string(18) "{imap.qq.com}INBOX"
/ / [1] = >
// string(26) "{imap.qq.com}Sent Messages"
/ / [2] = >
// string(19) "{imap.qq.com}Drafts"
/ / [3] = >
// string(29) "{imap.qq.com}Deleted Messages"
/ / [4] = >
// string(17) "{imap.qq.com}Junk"
/ / [5] = >
// string(51) "{imap.qq.com}&UXZO1mWHTvZZOQ-/[email protected]"
/ /}
Copy the code

The imap_list() function returns folder information in your mailbox, such as INBOX INBOX, Sent Messages, Drafts box, Deleted Messages, Junk trash, In addition, the mailbox folder 139 bound to my mailbox is also displayed.

$chk = (array) imap_mailboxmsginfo($mbox);
var_dump($chk);
// array(8) {
// ["Unread"]=>
// int(34)
// ["Deleted"]=>
// int(0)
// ["Nmsgs"]=>
// int(37)
// ["Size"]=>
// int(951128)
// ["Date"]=>
// string(37) "Wed, 16 Dec 2020 14:31:50 +0800 (CST)"
// ["Driver"]=>
// string(4) "imap"
// ["Mailbox"]=>
// string(54) "{imap.qq.com:993/imap/notls/ssl/user="149844827"}INBOX"
// ["Recent"]=>
// int(0)
/ /}
Copy the code

Imap_mailboxmsginfo () returns information in the current mailbox folder. As you can see from the returned field, we have 34 Unread messages. 37 new emails, size, access time, email information and other content.

Read operation message

Finally, we will focus on how to download and read the mail and perform some simple operations.

$all = imap_search($mbox."ALL");
var_dump($all);
// array(37) {
/ / [0] = >
// int(1)
/ / [1] = >
// int(2)
/ / [2] = >
// int(3)
/ / [3] = >
// int(4)
/ / [4] = >
// int(5)
/ /...
/ /...

foreach ($all as $m) {
    $headers = imap_fetchheader($mbox.$m);
    $rawBody = imap_fetchbody($mbox.$m, FT_UID);

    $headers = iconv_mime_decode_headers($headers.0."UTF-8");

    var_dump($headers);
    if (isset($headers['Content-Transfer-Encoding'&&])$headers['Content-Transfer-Encoding'] = ='base64') {
        $rawBody = imap_base64($rawBody);
    }
    var_dump($rawBody);

    if ($m= =1) {
        imap_mail_copy($mbox.$m."Drafts"); // Copy to the draft box
        imap_setflag_full($mbox.$m."Seen"); // Set it to read
    }

    if ($m= =2) {
        imap_delete($mbox.$m); / / delete
        imap_expunge($mbox);
    }
    if ($m= =3) {
        imap_mail_move($mbox.$m."Junk"); / / move
        imap_expunge($mbox); }}Copy the code

Imap_search () is used to find emails, and its second argument is a specified string, such as the ALL argument, which returns ALL messages. It can also be specified as DELETED, UNSEEN, and many other things. You can refer to the relevant documentation for a list of parameters. This function fetches all the mail numbers of the message, in fact, it is the number from 1 to 37.

Read the email

Imap_fetchheader () and imap_fetchBody () read the header and content of the message based on the message number, respectively. If printed normally, their content is encoded, which means we can’t see the content visually. Therefore, utF-8 decoding is required for the head file, and the mail Content is decoded according to the content-Transfer-Encoding field in the header. Here we only demonstrate the situation of base64 encoding, in fact, it has other encoding formats, interested students can consult their own information in-depth understanding.

// The first email
// headers
// array(13) {
// ["From"]=>
// string(29) "QQ mailbox team <[email protected]>"
// ["To"]=>
// string(29) "xxx 
      
       "
      @qq.com>
// ["Subject"]=>
// string(53) "More secure, more efficient, more powerful, all in QQ mailbox APP"
// ["Date"]=>
// string(31) "Wed, 16 Dec 2020 10:08:54 +0800"
// ["Message-ID"]=>
/ / string (38) 1608084534.3423313103 > < app_popularize. ""
// ["X-QQ-STYLE"]=>
// string(1) "1"
// ["X-QQ-SYSID"]=>
// string(9) "100000010"
// ["X-QQ-MIME"]=>
// string(21) "TCMime 1.0 by Tencent"
// ["X-QQ-Mailer"]=>
// string(10) "QQMail 2.x"
// ["X-QQ-mid"]=>
// string(30) "mmnez10417t1608084534tfekjqwx0"
// ["Content-Type"]=>
// string(26) "text/html; charset="utf-8""
// ["Content-Transfer-Encoding"]=>
// string(6) "base64"
// ["Mime-Version"]=>
/ / string (3) "1.0"
/ /}
Copy the code

The above content is the header information of the first email. It can be seen from the information content that Subject is the title of the email, which is an email sent by QQ mailbox system. From and To are the email addresses of the sender and the recipient respectively. Other important ones are content-Type and Content-Transfer-Encoding, which correspond to the document Type, character set Encoding, and conversion Encoding, respectively.

Different messages have different headers, but we’re just showing the simplest one here.

// rawBody
// string(5850) "
/ / 
      
// <html>
// <head>
// 
      
// imap
// 
// @media screen and (min-width: 700px) {
// .bottomErweima {
// display: block ! important;
/ /}
// #btn {
// display: none ! important;
/ /}
// .footer {
// display: none ! important;
/ /}
/ /}
// * Width: 980px for vivo cell phone with aspect-ratio < 1 */
// @media screen and (min-width: 700px) and (max-width: 1000px) and (max-aspect-ratio:1/1){
// .bottomErweima {
// display: none ! important;
/ /}
// #btn {
// display: block ! important;
/ /}
// .footer {
// display: block ! important;
/ /}
/ /}
// 
// </head>
// 
//   <div id="email-box" style="max-width: 550px;margin: 0 auto;">
// 
      
// 
      
// < p style =" max-width: 100%; clear: both; Here, you can log in to multiple email accounts, store wechat emails conveniently, and edit emails with multiple Windows...... There's more to explore! // / /... / /... Copy the code

The content of the message is simply HTML after being parsed using imap_base64(). This corresponds directly to the Content-Type in the header. Imap_base64 () is no different from base64_decode(), and there is no problem using base64_decode() directly. Of course, the premise is to determine whether the Content of the message is encoded using Base64 in content-Transfer-Encoding. Some emails may not even have this field.

Copy, move, and delete messages

Imap_mail_copy () is used to copy messages, and here we copy the first message into the draft box and mark it as read with imap_setFLAG_full (). It seems to have been read. There are other parameters, such as Deleted and Draft, that Seem to have been read.

The imap_delete() function is used to delete mail and imap_mail_move() is used to move files. Calling both functions requires imap_expunge() to synchronize operations online.

After doing this, you can directly see whether the online mail has changed accordingly.

conclusion

IMAP knowledge we will briefly learn, because in learning this content, I found that there are already a lot of online god door packaged classes can be directly copied down to use. In addition, its functions are very rich, and there are many functions that have not been introduced, such as the operation of attachments, I believe that you will gradually come into contact with their own learning and use of the process.

Test code:

Github.com/zhangyue050…

Reference Documents:

www.php.net/manual/zh/b…