How to fetch the mail content in php

In PHP, you can fetch the content of an email using the imap_open() and imap_fetchbody() functions. Here's an example:

Prerequisites:

  1. You need to have an IMAP (Internet Message Access Protocol) server set up on your server or have access to one.
  2. You need to have the imap extension enabled in your PHP configuration.

Example Code:

<?php

// Set up IMAP connection
$imap_host = 'imap.example.com';
$imap_port = 143;
$imap_username = 'your_email_username';
$imap_password = 'your_email_password';

$imap_conn = imap_open("{$imap_host}:{$imap_port}/novalidate-cert", $imap_username, $imap_password) or die("Cannot connect to IMAP server");

// Fetch the email message
$inbox = imap_open("inbox", $imap_username, $imap_password) or die("Cannot open inbox");
$message = imap_fetchbody($inbox, 1, 2); // Fetch the second message (index 1) and its body (part 2)

// Decode the email body
$message = imap_base64($message);

// Print the email content
echo $message;

// Close the IMAP connection
imap_close($imap_conn);

?>

Explanation:

  1. We set up the IMAP connection using imap_open() with the host, port, username, and password.
  2. We fetch the email message using imap_fetchbody() with the inbox name, message index (1-based), and part number (2 for the body).
  3. We decode the email body using imap_base64() to convert the base64-encoded content to plain text.
  4. We print the email content using echo.
  5. Finally, we close the IMAP connection using imap_close().

Note:

Remember to check the PHP documentation for more information on the imap extension and its functions.