Skip to content
PHP

Extracting Email Body and Sender Details from Gmail Using PHP (IMAP & cURL)

A
Author
Sep 21, 2020 · 7 min read
Extracting Email Body and Sender Details from Gmail Using PHP (IMAP & cURL)

Introduction

  • Automating email processing helps businesses handle customer inquiries, order confirmations, and contact form submissions efficiently.
  • Extracting relevant details from emails reduces manual efforts and improves response time.
  • This article demonstrates how to:
    • Connect to Gmail using PHP IMAP.
    • Retrieve unread emails and extract important details.
    • Process email content to fetch the sender’s name, email, subject, and message body.
    • Send extracted data to a CRM (FunnelMaker) via cURL API.

IMAP and Its Importance

  • IMAP (Internet Message Access Protocol) is used to fetch emails from a mail server.
  • Unlike POP3, IMAP does not delete emails from the server after retrieval.
  • It allows accessing emails from multiple devices simultaneously.

Setting Up Gmail for IMAP Access

  • Log in to Gmail.
  • Navigate to Settings > See all settings.
  • Select Forwarding and POP/IMAP.
  • Under IMAP access, choose Enable IMAP.
  • Click Save Changes.
  • Generate an App Password if using two-factor authentication (2FA).

PHP Code to Connect to Gmail via IMAP

<?php
$hostname = '{imap.gmail.com:993/imap/ssl/novalidate-cert}';
$username = 'your-email@gmail.com';
$password = 'your-app-password';

// Establish connection
$inbox = imap_open($hostname, $username, $password) or die('Cannot connect to Gmail: ' . imap_last_error());
  • $hostname specifies Gmail’s IMAP server.
  • $username is the email address.
  • $password is the Gmail password or App Password if 2FA is enabled.
  • imap_open() establishes a connection to Gmail’s IMAP server.

Fetching Unread Emails

$emails = imap_search($inbox, 'UNSEEN');

if ($emails) {
    foreach ($emails as $email_number) {
        $overview = imap_fetch_overview($inbox, $email_number, 0);
        $message = imap_fetchbody($inbox, $email_number, 1);
        echo "From: " . $overview[0]->from . "<br>";
        echo "Subject: " . $overview[0]->subject . "<br>";
        echo "Message: " . $message . "<br><hr>";
    }
}

imap_close($inbox);
?>
  • imap_search($inbox, 'UNSEEN') fetches unread emails.
  • imap_fetch_overview() retrieves email metadata (sender, subject).
  • imap_fetchbody() extracts the email message body.
  • imap_close() closes the connection to prevent resource leaks.

Extracting Specific Email Details

  • The email body contains raw text, requiring string processing to extract key details.
  • A function can be used to extract specific sections of an email:
function get_string_between($string, $start, $end) {
    $string = ' ' . $string;
    $ini = strpos($string, $start);
    if ($ini == 0) return '';
    $ini += strlen($start);
    $len = strpos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}

$sender_name = get_string_between($message, 'From:', 'Email:');
$sender_email = get_string_between($message, 'Email:', 'Subject:');
$email_subject = get_string_between($message, 'Subject:', 'Message Body:');
$email_body = get_string_between($message, 'Message Body:', 'This e-mail was sent from');
  • get_string_between() extracts content between specified keywords.
  • The function is used to get sender name, email, subject, and message body.

Sending Extracted Data to a CRM (FunnelMaker) Using cURL

  • After extracting email details, they can be sent to an external CRM for processing.
  • cURL is used to send an HTTP POST request with the extracted data.
function sendToCRM($name, $email, $subject, $messageBody) {
    $form_url = "https://app.funnelmaker.com/xml.pl";
    
    $data_to_post = array(
        'email' => "dev***jk1@funnelmaker.com",
        'password' => "dev*****1",
        'xml' => "<Contact><Name>$name</Name><Email>$email</Email><Subject>$subject</Subject><Message>$messageBody</Message></Contact>"
    );

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $form_url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data_to_post);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

    $result = curl_exec($curl);
    curl_close($curl);

    return $result;
}

$response = sendToCRM($sender_name, $sender_email, $email_subject, $email_body);
echo "CRM Response: " . $response;

$form_url is the API endpoint of the CRM. curl_setopt() sets up the HTTP POST request. curl_exec() sends the request and retrieves the response.

Error Handling and Debugging

  • Check Connection Errors:
if (!$inbox) {
    die('IMAP Connection Error: ' . imap_last_error());
}

Verify API Response:

if (strpos($response, 'Success') !== false) {
    echo "Data successfully sent to CRM.";
} else {
    echo "Error: " . $response;
}
  • Enable cURL Debugging:
curl_setopt($curl, CURLOPT_VERBOSE, true);

Security Considerations

  • Use App Passwords instead of storing raw Gmail passwords.
  • Validate extracted data to prevent API errors.
  • Limit IMAP requests to avoid rate limits.

Performance Optimization

  • Batch processing: Process multiple emails in one script execution.
  • Caching: Store processed email IDs to prevent reprocessing.
  • Parallel execution: Use cron jobs to automate periodic execution.

Conclusion

  • PHP IMAP functions allow efficient email retrieval from Gmail.
  • Extracting sender details, subject, and message body is crucial for automation.
  • cURL API integration enables sending extracted data to a CRM system.
  • Implementing error handling and security ensures a robust solution.

Final Code

<?php connect('{imap.gmail.com:993/imap/ssl/novalidate-cert}', 'kanemfgcontactus@gmail.com', '0Gfd60uwHOJ4'))
{
    $inbox = $email->getMessages('html');
}

//print_r($inbox['data']); if($inbox ==null){     echo 'not Connect'; }else{     if(count($inbox['data'])>0){         foreach($inbox['data'] as $mail){             //$statuss = imap_setflag_full($connectionn, $mail['uid'], "\\Seen \\Flagged", ST_UID);             //echo $mail['message'];             foreach(preg_split("/((\r?\n)|(\r\n?))/", $mail['message']) as $line){                 if(strpos($line,'From:') !== false){                     $Name=explode('From:',$line);                  // echo $Name[1];                 }                 if(strpos($line,'Email:') !== false){                     $Email=explode('Email:',$line);                     // echo $Email[1];                 }                 if(strpos($line,'Subject:') !== false){                     $Subject=explode('Subject:',$line);                  // echo $Subject[1];                 }             }             $MessageBody = get_string_between($mail['message'], 'Message Body:', 'This e-mail was sent from a contact form on www.kanemfg.com');            /* foreach(preg_split('/<(.*?)>/u', $mail['message']) as $line){                 //echo print_r($line);                 if(strpos($line,'Message Body:') !== false){                     print_r($line);                     $Emaill=explode('Message Body:',$line);                     $Email=preg_split('/<(.*?)>/u', $Emaill[1]) ;                     //print_r($Email);                 }             }*/                 createContact($Name[1],$Email[1],$Subject[1],$MessageBody);             }     }else{      } } function createContact($Name,$Email,$Subject,$MessageBody) {     die("dddd");;  $msg=''; $form_url = "https://app.funnelmaker.com/xml.pl"; // This is the data to POST to the form. The KEY of the array is the name of the field. The value is the value posted. $data_to_post = array(); $data_to_post['email'] ="dev**jk1@funnelmaker.com"; $data_to_post['password'] ="dev****1"; $data_to_post['xml'] = ""; // Initialize cURL $curl = curl_init(); // Set the options curl_setopt($curl,CURLOPT_URL, $form_url); // This sets the number of fields to post curl_setopt($curl,CURLOPT_POST, sizeof($data_to_post)); // This is the fields to post in the form of an array. curl_setopt($curl,CURLOPT_POSTFIELDS, $data_to_post); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); //execute the post $result= curl_exec($curl); $xml = new SimpleXMLElement($result); $tocken = $xml->Token; $success = $xml->Result; $tknerror=$xml->ErrorText;    if(isset($FullName) && !empty($FullName)  && isset($EmailAddress) && !empty($EmailAddress)){          $fullform="                                                                                       ".ltrim(strip_tags($FullName))."                                 ".ltrim(strip_tags($CompanyName))."                                 ".ltrim(strip_tags($Title))."                                 ".ltrim(strip_tags($EmailAddress))."                                 ".ltrim(strip_tags($PhoneNumber))."                                 ".ltrim(strip_tags($Address1))."                                 ".ltrim(strip_tags($City))."                                 ".ltrim(strip_tags($State))."                                 ".ltrim(strip_tags($Zip))."                                                                      ".ltrim(strip_tags($Industry))."                                                                                                       kanemfgcontactus form                                                                                                            ";//WARM Inbound Leads from Neuton         if($success=="Success"){             $data_to_posts = array();             $data_to_posts['email'] ="dev1@funnelmaker.com";             $data_to_posts['auth_token'] = "$tocken";             $data_to_posts['xml'] = "$fullform";              /*echo "";            print_r($fullform);die;*/             // Initialize cURL             $curl = curl_init();             // Set the options             curl_setopt($curl,CURLOPT_URL, $form_url);             // This sets the number of fields to post             curl_setopt($curl,CURLOPT_POST, sizeof($data_to_posts));             // This is the fields to post in the form of an array.             curl_setopt($curl,CURLOPT_POSTFIELDS, $data_to_posts);             curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);             //execute the post             $resultnew= curl_exec($curl);             $xmlnew = new SimpleXMLElement($resultnew);            /*echo "";            print_r($xmlnew);*/             $textResult=$xmlnew->Contacts->Contact->Result;             $textResulterror=$xmlnew->Contacts->Contact->ErrorText;             $Contact_id=$xmlnew->Contacts->Contact->Contact_id;             if($textResult=='Success'){                 echo json_encode(array('status'=>200,'msg'=>'your registration Successfully'));             }else{                 echo json_encode(array('status'=>402,'msg'=>$textResulterror));             }         }else{            echo json_encode(array('status'=>403,'msg'=>$tknerror));         }     }else{     echo json_encode(array('status'=>403,'msg'=>'You did not fill out the required fields'));     } } function get_string_between($string, $start, $end){     $string = ' ' . $string;     $ini = strpos($string, $start);     if ($ini == 0) return '';     $ini += strlen($start);     $len = strpos($string, $end, $ini) - $ini;     return substr($string, $ini, $len); }
 ?>

A
Author

Author at The Creative Coders.

The monthly build log

One email a month. New posts, lessons, and the occasional strong opinion. No spam.