imap库_探索PHP IMAP库,第1部分

imap库

Some web applications might require features of an email client to be made available the users. In these situations, we can either write our own or customize opensource clients like SquirrelMail or Roundcube. Regardless of what you choose, knowledge of working with the PHP IMAP mail extension will be helpful.

某些Web应用程序可能要求电子邮件客户端的功能对用户可用。 在这种情况下,我们可以编写自己的代码或自定义开源客户端,例如SquirrelMail或Roundcube。 无论您选择什么,都将对使用PHP IMAP邮件扩展名的知识有所帮助。

In this two-part series I’ll explain how to work with the IMAP extension. This is the first part which discusses the necessary functions for connecting to mail servers and reading messages. The second part will talk about actions for working with email, like deleting messages, downloading attachments, etc.

在这个由两部分组成的系列文章中,我将解释如何使用IMAP扩展。 这是第一部分,讨论了连接到邮件服务器和阅读邮件的必要功能。 第二部分将讨论使用电子邮件的操作,例如删除邮件,下载附件等。

To demonstrate functionality, I’ll use code samples that can be used to start scripting your own mail client. I’ll assume a single web script which uses these URL parameters to call the necessary functions:

为了演示功能,我将使用可用于开始编写自己的邮件客户端脚本的代码示例。 我假设一个使用以下URL参数调用必要功能的Web脚本:

  • func – the type of functionality required (ex: read email, view inbox, delete message)

    func –所需func的类型(例如:阅读电子邮件,查看收件箱,删除邮件)

  • folder – the name of the mailbox folder to connect to (ex: inbox, sent, spam)

    folder –要连接的邮箱文件folder的名称(例如:收件箱,已发送,垃圾邮件)

  • uid – the unique ID of the email targeted

    uid –目标电子邮件的唯一ID

The parameters can be retrieved using $_GET and a switch statement can be used to invoke the appropriate actions.

可以使用$_GET检索参数,并可以使用switch语句调用适当的操作。

<?php
$func = (!empty($_GET["func"])) ? $_GET["func"] : "view";
$folder = (!empty($_GET["folder"])) ? $_GET["folder"] : "INBOX";
$uid = (!empty($_GET["uid"])) ? $_GET["uid"] : 0;

// connect to IMAP
// ...

switch ($func) {
    case "delete":
        deleteMail($imap, $folder, $uid);
        break;

    case "read":
        deleteMail($imap, $folder, $uid);
        break;

    case "view":
    default:
        viewMail($imap, $folder);
        break;
}

连接到IMAP (Connecting to IMAP)

To establish a connection to the IMAP server, we use the imap_connect() function as shown here:

要建立与IMAP服务器的连接,我们使用imap_connect()函数,如下所示:

<?php
$imap = imap_open($mailboxPath, $username, $password);

The mailbox path, username, and password strings are required parameters to connect to the server. You can learn about the optional parameters in the manual.

邮箱路径,用户名和密码字符串是连接到服务器的必需参数。 您可以在手册中了解可选参数。

The mailbox path is a string that identifies server and port information in braces followed by the name of the desired mail folder. Here are a few strings for the inbox folder for popular mail providers:

邮箱路径是一个字符串,用大括号标识服务器和端口信息,后跟所需邮件文件夹的名称。 以下是流行邮件提供商的收件箱文件夹的一些字符串:

  • Gmail {imap.gmail.com:993/imap/ssl}INBOX

    Gmail {imap.gmail.com:993/imap/ssl}INBOX

  • Yahoo {imap.mail.yahoo.com:993/imap/ssl}INBOX

    雅虎{imap.mail.yahoo.com:993/imap/ssl}INBOX

  • AOL {imap.aol.com:993/imap/ssl}INBOX

    美国在线{imap.aol.com:993/imap/ssl}INBOX

Some servers do not have SSL enabled, in which case you would omit “SSL” from the string. Other servers might use self-signed certificates, in which you would include “novalidate-cert”.

某些服务器未启用SSL,在这种情况下,您将在字符串中省略“ SSL”。 其他服务器可能使用自签名证书,其中包括“ novalidate-cert”。

<?php
$imap = imap_open("{localhost:993/imap/ssl/novalidate-cert}", "username", "password");

With an open connection to the mail server, now we can look at the functions used for the following activities:

通过与邮件服务器的开放连接,现在我们可以查看用于以下活动的功能:

  • Displaying the list of mailbox folders in your email account

    显示您的电子邮件帐户中的邮箱文件夹列表
  • Displaying the list of email messages in the folder

    显示文件夹中的电子邮件列表
  • Viewing the email’s content

    查看电子邮件的内容

列出文件夹 (Listing the Folders)

Inbox, sent, trash, and spam folders are seen in pretty much every email account, and users can often create custom folders as well. In order to view messages in these folders, we need to change our connection string. For example, I used “INBOX” in the path string earlier. If I wanted to connect to the spam folder, I might want to use something like “Spam” instead. But even though it might be listed as Spam in your email account when viewed through a mail client, the real folder name might be different behind the scenes. We can list all of the available folders in an account using imap_list().

收件箱,已发送,垃圾箱和垃圾邮件文件夹几乎在每个电子邮件帐户中都可以看到,用户通常也可以创建自定义文件夹。 为了查看这些文件夹中的消息,我们需要更改我们的连接字符串。 例如,我之前在路径字符串中使用了“ INBOX”。 如果我想连接到垃圾邮件文件夹,则可能要使用“垃圾邮件”之类的名称。 但是,即使通过邮件客户端查看时,它可能在您的电子邮件帐户中被列为“垃圾邮件”,但实际的文件夹名称可能在幕后有所不同。 我们可以使用imap_list()列出帐户中所有可用的文件夹。

<?php
$folders = imap_list($imap, "{imap.gmail.com:993/imap/ssl}", "*");
echo "<ul>";
foreach ($folders as $folder) {
    $folder = str_replace("{imap.gmail.com:993/imap/ssl}", "", imap_utf7_decode($folder));
    echo '<li><a href="mail.php?folder=' . $folder . '&func=view">' . $folder . '</a></li>';
}
echo "</ul>";

We have to pass the connection handle obtained with imap_open() as the initial parameter to imap_list(). We also need to pass a bare path sting (without the folder, e.g. “INBOX”). The star as the third parameter requests all of the available folders.

我们必须用得到的连接句柄传递imap_open()作为初始参数imap_list() 我们还需要传递一个空路径字符串(没有文件夹,例如“ INBOX”)。 星号作为第三个参数请求所有可用文件夹。

列出电子邮件 (Listing Email Messages)

Each folder has a list of available email messages, so let’s see how we can generate a listing of the messages in our inbox.

每个文件夹都有一个可用电子邮件列表,因此,让我们看看如何在收件箱中生成邮件列表。

We need to first get the number of messages available using imap_num_msg(). Then we can use the imap_header() function to get the header information for each message.

我们首先需要使用imap_num_msg()获得可用消息的数量。 然后,我们可以使用imap_header()函数获取每个消息的标题信息。

Let’s say if we wanted to the last 20 emails:

假设我们要发送最近20封电子邮件:

<?php
$numMessages = imap_num_msg($imap);
for ($i = $numMessages; $i > ($numMessages - 20); $i--) {
    $header = imap_header($imap, $i);

    $fromInfo = $header->from[0];
    $replyInfo = $header->reply_to[0];

    $details = array(
        "fromAddr" => (isset($fromInfo->mailbox) && isset($fromInfo->host))
            ? $fromInfo->mailbox . "@" . $fromInfo->host : "",
        "fromName" => (isset($fromInfo->personal))
            ? $fromInfo->personal : "",
        "replyAddr" => (isset($replyInfo->mailbox) && isset($replyInfo->host))
            ? $replyInfo->mailbox . "@" . $replyInfo->host : "",
        "replyName" => (isset($replyTo->personal))
            ? $replyto->personal : "",
        "subject" => (isset($header->subject))
            ? $header->subject : "",
        "udate" => (isset($header->udate))
            ? $header->udate : ""
    );

    $uid = imap_uid($imap, $i);

    echo "<ul>";
    echo "<li><strong>From:</strong>" . $details["fromName"];
    echo " " . $details["fromAddr"] . "</li>";
    echo "<li><strong>Subject:</strong> " . $details["subject"] . "</li>";
    echo '<li><a href="mail.php?folder=' . $folder . '&uid=' . $uid . '&func=read">Read</a>';
    echo " | ";
    echo '<a href="mail.php?folder=' . $folder . '&uid=' . $uid . '&func=delete">Delete</a></li>';
    echo "</ul>";
}

The $imap connection should be open to the desired folder. We can then traverse through the last 20 emails using the number of messages received by imap_num_msg(). The connection and email number are given to imap_header() to retrieve the header information, which can then be parsed for the interesting details like the sender’s email address and name, subject, etc.

$imap连接应该打开到所需的文件夹。 然后,我们可以使用imap_num_msg()收到的邮件数量遍历最后20封电子邮件。 将连接和电子邮件号码提供给imap_header()以检索标头信息,然后可以对标头信息进行解析以获取有趣的详细信息,例如发件人的电子邮件地址和姓名,主题等。

Note that the email number we get from using the total message count is not a unique ID for the message. If you have 100 emails in your inbox, then the last number will be 100, the previous will be 99, and so on. But its not unique. If you delete message number 100 and then receive a new message, it’s number will also will be 100.

请注意,我们从邮件总数中获得的电子邮件号码不是邮件的唯一ID。 如果收件箱中有100封电子邮件,则最后一个数字为100,前一个为99,依此类推。 但是它不是唯一的。 如果您删除消息编号100,然后收到新消息,则该消息编号也将为100。

We have to get the unique ID for an email in order to proceed with other actions. Each email does have an unique ID, called UID, which we can get by providing the email number to the imap_uid() function. The UID is unique and will not change over time.

我们必须获取电子邮件的唯一ID,才能继续执行其他操作。 每封电子邮件确实都有一个唯一的ID,称为UID,我们可以通过将电子邮件号提供给imap_uid()函数来获得该imap_uid() 。 UID是唯一的,不会随时间变化。

查看邮件内容 (Viewing Message Contents)

Reading email is not really as simple as the previous tasks, so I’m going to use the Receive Mail class developed by Mitul Koradia as a starting point to help make things easier. From the class I’ve extracted and adapted the following three functions for our example here:

阅读电子邮件并不像以前的任务那么简单,因此我将使用Mitul Koradia开发的Receive Mail类作为帮助简化事情的起点。 从类中,我为这里的示例提取并改编了以下三个函数:

<?php
function getBody($uid, $imap) {
    $body = get_part($imap, $uid, "TEXT/HTML");
    // if HTML body is empty, try getting text body
    if ($body == "") {
        $body = get_part($imap, $uid, "TEXT/PLAIN");
    }
    return $body;
}

function get_part($imap, $uid, $mimetype, $structure = false, $partNumber = false) {
    if (!$structure) {
           $structure = imap_fetchstructure($imap, $uid, FT_UID);
    }
    if ($structure) {
        if ($mimetype == get_mime_type($structure)) {
            if (!$partNumber) {
                $partNumber = 1;
            }
            $text = imap_fetchbody($imap, $uid, $partNumber, FT_UID);
            switch ($structure->encoding) {
                case 3: return imap_base64($text);
                case 4: return imap_qprint($text);
                default: return $text;
           }
       }

        // multipart 
        if ($structure->type == 1) {
            foreach ($structure->parts as $index => $subStruct) {
                $prefix = "";
                if ($partNumber) {
                    $prefix = $partNumber . ".";
                }
                $data = get_part($imap, $uid, $mimetype, $subStruct, $prefix . ($index + 1));
                if ($data) {
                    return $data;
                }
            }
        }
    }
    return false;
}

function get_mime_type($structure) {
    $primaryMimetype = array("TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER");

    if ($structure->subtype) {
       return $primaryMimetype[(int)$structure->type] . "/" . $structure->subtype;
    }
    return "TEXT/PLAIN";
}

The getBody() function gets the email’s content by passing its UID and the IMAP connection. Inside the function, we call the get_part() function with the content type as TEXT/HTML. Plain text emails are much easier to read. So we first try to find the HTML content inside the email.

getBody()函数通过传递其UID和IMAP连接来获取电子邮件的内容。 在函数内部,我们调用内容类型为TEXT / HTML的get_part()函数。 纯文本电子邮件更易于阅读。 因此,我们首先尝试在电子邮件中查找HTML内容。

Then we read the structure of the email using imap_fetchstructure() function. This function would have taken the email number by default, but we changed the library function to use the UID instead by passing the FT_UID constant.

然后,我们使用imap_fetchstructure()函数读取电子邮件的结构。 默认情况下,此函数将使用电子邮件号码,但是我们通过传递FT_UID常量将库函数更改为使用UID。

Then we get the mime type of the email message using the get_mime_type() function. There are eight mime types returned by this function as integers:

然后,我们使用get_mime_type()函数获得电子邮件的mime类型。 此函数以整数形式返回八种mime类型:

  • 0 – TEXT

    0 –文字
  • 1 – MULTIPART

    1 –多重
  • 2 – MESSAGE

    2 –讯息
  • 3 – APPLICATION

    3 –应用
  • 4 – AUDIO

    4 –音频
  • 5 – IMAGE

    5 –图片
  • 6 – VIDEO

    6 –视频
  • 7 – OTHER

    7 –其他

We convert the returned integer into actual mime type string using the mime types array.

我们使用mime types数组将返回的整数转换为实际的mime类型字符串。

Multipart messages can have a large number of subtypes, so we traverse recursively through all of the subtypes using the part numbers and retrieve the email content using imap_fetchBody() when the correct part is found using the mime type.

分段消息可能具有大量的子类型,因此,当使用mime类型找到正确的部分时,我们使用零件号来遍历所有子类型,并使用imap_fetchBody()检索电子邮件内容。

Then, we use an appropriate decode function according to the encoding type of the message and return the content. A complete list of available encoding types is shown here:

然后,我们根据消息的编码类型使用适当的解码函数并返回内容。 此处显示可用编码类型的完整列表:

  • 0 – 7BIT

    0 – 7位
  • 1 – 8BIT

    1 – 8位
  • 2 – BINARY

    2 –二进制
  • 3 – BASE64

    3 – BASE64
  • 4 – QUOTED-PRINTABLE

    4 –报价PRINTABLE
  • 5 – OTHER

    5 –其他

摘要 (Summary)

We started this series by reviewing the basics of connecting to IMAP servers, then moved on to listing message inside available folders, and finished with reading an email message’s content. In the next part I’ll discuss the functions which can be used to implement additional functionality expected from an email client, like deleting messages and handling attachments.

我们通过回顾连接到IMAP服务器的基础知识开始了本系列文章,然后继续列出可用文件夹中的消息,最后阅读了电子邮件的内容。 在下一部分中,我将讨论可用于实现电子邮件客户端期望的其他功能的功能,例如删除消息和处理附件。

Image via Fotolia

图片来自Fotolia

翻译自: https://www.sitepoint.com/exploring-phps-imap-library-1/

imap库

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值