How to retrive gmail mails in php wampserver

To retrieve Gmail emails using PHP on a WAMP server, you'll need to use the PHP IMAP extension, which allows you to connect to an IMAP server and retrieve emails. Here's a step-by-step guide to help you get started:

Prerequisites:

  1. WAMP server installed on your local machine.
  2. PHP IMAP extension enabled. You can check if it's enabled by running phpinfo() in your PHP file and looking for the "IMAP" section.
  3. A Gmail account with IMAP enabled. You can enable IMAP in your Gmail settings by going to Settings > Forwarding and POP/IMAP > Enable IMAP.

Step 1: Install the PHP IMAP extension (if not already installed)

If the PHP IMAP extension is not already installed, you can install it using the following steps:

  1. Open the WAMP server control panel and click on "PHP" > "PHP Extensions".
  2. Click on the "Install" button next to "IMAP".
  3. Follow the installation instructions to complete the installation.

Step 2: Configure your PHP script to connect to Gmail using IMAP

Create a new PHP file (e.g., gmail.php) and add the following code:

<?php
// Set your Gmail credentials
$username = '[email protected]';
$password = 'your_password';

// Set the IMAP server and port
$imap_server = '{imap.gmail.com:993/imap/ssl}INBOX';

// Connect to the IMAP server
$imap = imap_open($imap_server, $username, $password) or die('Cannot connect to IMAP server');

// Retrieve the email headers
$headers = imap_headers($imap);

// Loop through the email headers and print the subject and sender
foreach ($headers as $header) {
    $subject = imap_headerinfo($imap, $header)->subject;
    $from = imap_headerinfo($imap, $header)->from[0]->mailbox. '@'. imap_headerinfo($imap, $header)->from[0]->host;
    echo "Subject: $subject\n";
    echo "From: $from\n\n";
}

// Close the IMAP connection
imap_close($imap);
?>

Replace [email protected] and your_password with your actual Gmail credentials.

Step 3: Run the PHP script

Open a web browser and navigate to http://localhost/gmail.php (assuming you saved the file in the www directory of your WAMP server). The script should connect to your Gmail account using IMAP and retrieve the email headers. The output should display the subject and sender of each email in your inbox.

Note: Make sure to enable less secure apps in your Gmail settings to allow PHP to connect to your account. You can do this by going to Settings > Accounts > Less secure app access > Turn on.