Home > Backend Development > PHP Tutorial > Detailed process of using PHP to receive mailbox emails using IMAP protocol

Detailed process of using PHP to receive mailbox emails using IMAP protocol

WBOY
Release: 2023-05-22 10:02:01
Original
2516 people have browsed it

As email plays an increasingly important role in our lives, people's demand for how to receive and manage email is also increasing. PHP, as a commonly used programming language, can receive and operate emails through the IMAP protocol. This article will introduce the detailed process of using PHP to receive mailbox emails using the IMAP protocol to help readers quickly understand the steps to implement this function.

Step 1: Connect to the mailbox server

Before using the IMAP protocol to receive mail, you need to create a session to connect to the mailbox server. This step can be easily accomplished using PHP's built-in imap_open() function. Usually, you need to provide the following information to connect to the email server:

  • The host name of the email server
  • The port number when using the IMAP protocol (default is 993)
  • Email account Username and password

For example, the following code implements a session to connect to the Gmail mailbox server:

$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'your_email@gmail.com';
$password = 'your_password';

$mailbox = imap_open($hostname, $username, $password) 
  or die('Cannot connect to Gmail: ' . imap_last_error());
Copy after login

Step 2: Select the mailbox folder

After successful connection , you need to select the mailbox folder to receive emails. The IMAP protocol allows us to create multiple folders on the email server, such as: Inbox, Sent, Trash, Drafts, etc. Use the imap_reopen() function to switch between different mailbox folders during a session. For example, the following code switches the current folder to the inbox:

$folder = 'INBOX';
imap_reopen($mailbox, $hostname . $folder) or die('Cannot open folder: ' . $folder);
Copy after login

Step 3: Get the mailing list

Next, we need to get the mailing list in the current mailbox folder. Use the imap_search() function to implement simple email searches, such as searching for unread emails, read emails, emails with specific topics, etc. The following code shows how to get the unread mail list:

$unseen_emails = imap_search($mailbox, 'UNSEEN');
Copy after login

If you want to get all emails, you can set the search condition to 'ALL':

$emails = imap_search($mailbox, 'ALL');
Copy after login

imap_search() function returns an email An array of identifiers, each identifier represents an email and can be used for subsequent operations.

Step 4: Parse the email content

After obtaining the email identifier array, you can use the imap_fetchstructure() function to obtain the structure of the email body. For text emails, its structure only has a simple text part; for HTML emails, attachment emails, etc., its structure may be more complex. Therefore, we need to parse the structure of the email body and extract relevant information as needed, such as sender, recipient, subject, body content, attachments, etc.

The following code shows how to parse the email content:

foreach ($emails as $email) {
  $structure = imap_fetchstructure($mailbox, $email);

  $from = $this->parseAddress($this->findHeader($structure, 'from'));
  $to = $this->parseAddress($this->findHeader($structure, 'to'));
  $subject = $this->findHeader($structure, 'subject');
  $body = '';

  if ($structure->encoding === 0) {
    // 解析纯文本邮件
    $body = imap_fetchbody($mailbox, $email, 1);
  } else {
    // 解析HTML邮件
    $parts = $this->getParts($structure);

    foreach ($parts as $part) {
      if ($part['subtype'] === 'PLAIN') {
        $body = imap_fetchbody($mailbox, $email, $part['partnum']);
      } else if ($part['subtype'] === 'HTML') {
        $body = imap_fetchbody($mailbox, $email, $part['partnum'], FT_UID | FT_PEEK);
      }
    }
  }

  // 处理邮件内容,例如保存到数据库、发送回执等等
}

function findHeader($structure, $header_name) {
  foreach ($structure->parts as $part) {
    if (isset($part->parameters) && $part->parameters[0]->attribute == $header_name) {
      return $part->parameters[0]->value;
    }
  }

  return '';
}

function getParts($structure) {
  $parts = [];

  if ($structure->parts) {
    foreach ($structure->parts as $index => $substructure) {
      $parts[$index] = [
        'ctype' => $substructure->ctype,
        'encoding' => $substructure->encoding,
        'subtype' => $substructure->subtype,
        'partnum' => ($index + 1)
      ];

      if (isset($substructure->params['name'])) {
        $parts[$index]['filename'] = $substructure->params['name'];
      }
    }
  } else {
    $parts[0] = [
      'ctype' => $structure->ctype,
      'encoding' => $structure->encoding,
      'subtype' => $structure->subtype,
      'partnum' => 1
    ];

    if (isset($structure->params['name'])) {
      $parts[0]['filename'] = $structure->params['name'];
    }
  }

  return $parts;
}

function parseAddress($address) {
  $name = '';
  $email = '';

  foreach (imap_rfc822_parse_adrlist($address, '') as $addr) {
    if (isset($addr->mailbox) && isset($addr->host)) {
      $name = $addr->personal;
      $email = $addr->mailbox . '@' . $addr->host;
    }
  }

  return [
    'name' => $name,
    'email' => $email
  ];
}
Copy after login

Step 5: Close the connection

After the operation is completed, don’t forget to close the connection with the mailbox server to release resources and protect account information. This step can be accomplished using the imap_close() function.

imap_close($mailbox);
Copy after login

To sum up, the process of PHP using IMAP protocol to receive mailbox mail can be summarized into the following five steps: connect to the mailbox server, select the mailbox folder, obtain the mail list, parse the mail content, and close the connection. Readers can use these codes to practice and expand to build their own email receiving system.

The above is the detailed content of Detailed process of using PHP to receive mailbox emails using IMAP protocol. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template