How to get main email from reply mail php

A common question!

When you receive a reply email, the From header of the reply email typically contains the email address of the original sender, not the reply sender. To extract the main email address from a reply email in PHP, you can use the following approaches:

  1. Using imap extension:

    <?php
    $imap = imap_open("{imap.gmail.com:993/imap/ssl}INBOX", "[email protected]", "your_password");
    $message = imap_fetchbody($imap, $message_id, 2); // 2 is the part number for the message body
    $from_header = imap_headerinfo($imap, $message_id)->from;
    $main_email = explode("<", $from_header)[1]; // extract the email address from the From header
    imap_close($imap);
    ?>

    In this example, we use the imap extension to connect to the IMAP server, fetch the message body, and extract the From header. We then use a regular expression to extract the email address from the From header.

  2. Using imap extension with imap_headerinfo:

    <?php
    $imap = imap_open("{imap.gmail.com:993/imap/ssl}INBOX", "[email protected]", "your_password");
    $message = imap_fetchbody($imap, $message_id, 2); // 2 is the part number for the message body
    $header_info = imap_headerinfo($imap, $message_id);
    $from_header = $header_info->from[0]->mailbox. "@". $header_info->from[0]->host;
    $main_email = $from_header;
    imap_close($imap);
    ?>

    In this example, we use the imap_headerinfo function to get the From header information, and then extract the email address from the mailbox and host properties.

  3. Using SwiftMailer library:

    
    <?php
    require_once 'SwiftMailer/Swift.php';

$message = Swift_Message::newInstance(); $message->setBody($reply_email_body); $from_header = $message->getHeaders()->get('From'); $main_email = $from_header->getAddress()->getAddress(); ?>


In this example, we use the `SwiftMailer` library to create a new message object and set the reply email body. We then use the `getHeaders` method to get the `From` header, and the `getAddress` method to extract the email address from the `From` header.

Note that these examples assume you have the `imap` extension installed and configured on your PHP server. Additionally, you may need to adjust the code to fit your specific use case and email server configuration.