Fetch Mails from Gmail in Core PHP

|
| By Webner

Fetch Mails in Core PHP

  1. Create an Core php app on console (https://console.developers.google.com).
  2. Download Google Client library from the following link (https://github.com/googleapis/google-api-php-client)
  3. Download the file of credentials(client_id,client_secret) and put it in the project directory.
  4. Create the config file in the root directory and paste the below code.

    <?php
    //path of autoload file
    require_once 'vendor/autoload.php';
    $client = new Google_Client();
    $client->setAuthConfig('filename of credentials');
    $client->addScope(Google_Service_Gmail::MAIL_GOOGLE_COM);
    $client->addScope('email');
    $client->addScope('profile');
    $client->setRedirectUri('RedirectURL that you saved in console app');
    $client->setAccessType('offline');
    $client->setApprovalPrompt("force");
    ?>

  5. Enable Gmail API.

    Core

    Search for Gmail and click on Gmail API

    google-api

    gmail-api

  6. Create google_connect_file and paste below code(Login Button )

    Include config file
    $login_button= "";
    if(isset($_GET["code"])){
    $token = $client->fetchAccessTokenWithAuthCode($_GET["code"]);
    if(!isset($token["error"])){
    $client->setAccessToken($token);
    $_SESSION["access_token"] = $token;
    //also save in the database if you want a session with google only end when you logout.
    }else{
    header('logout from google');
    }
    }
    if(!$_SESSION["access_token"]){
    $login_button = '<div class="forgot-link display-inline-block ">
    <a href="'.$client->CreateAuthUrl().'" class="google social-login-btn google-login"><i class="fa fa-google fa-fw"></i> Login with Google </a>
    </div>';
    }
    if( $login_Button==””){
    <a style="color: #337AB7;font-weight:bold;font-size:16px" href="link to page to view emails">View Emails </a>   <a style="color: #337AB7" class="loginButton" href=" link to logout page" > Logout </a>
    }esle{
    echo $login_Button;
    }

  7. Create a file for fetching emails from Gmail and paste below code

    Include config file created on the top
    $gmail = new Google_Service_Gmail($client);
    $search = "category:primary label:inbox";
    $inboxMessage = [];
    try{
    $params = array();
    $params = array('maxResults'=>50,'q'=>$search);
    if($_POST['nextpagetoken'] != 0){
    $params['pageToken'] = $token;
    }
    $list = $gmail->users_messages->listUsersMessages('me',$params);
    $email = $gmail->users->getProfile('me')->getEmailAddress( );
    $messageList = $list->getMessages();
    $nextpagetoken = $list->getNextPageToken( );
    foreach($messageList as $mlist){
    $optParamsGet2['format'] = 'full';
    $single_message = $gmail->users_messages->get('me',$mlist->id, $optParamsGet2);
    $body = msg_body_recursive($single_message->getPayload());
    $body_data = array_key_exists('html', $body) ? $body['html'] : $body['plain'];
    $message_id = $mlist->id;
    $headers = $single_message->getPayload()->getHeaders();
    $snippet = $single_message->getSnippet();
    $message_subject = "";
    $message_date = "";
    $sender = "";
    $message_to = "";
    foreach($headers as $single) {
    if ($single->getName() == 'Subject') {
    $message_subject = $single->getValue();
    }
    else if ($single->getName() == 'Date') {
    $message_date = $single->getValue();
    $message_date = date('m/d/yy h:m A', strtotime($message_date));
    }
    else if ($single->getName() == 'From') {
    $sender = htmlentities($single->getValue());
    }else if ($single->getName() == 'To') {
    $message_to = $single->getValue();
    $message_to = str_replace('"', '', $message_to);
    }
    }
    $messageId = GetMessageWithId($message_id);
    if(!count($messageId)){
    $inboxMessage[] = [
    'messageId' => $message_id,
    'messageSnippet' => $snippet,
    'messageSubject' => $message_subject,
    'messageDate' => $message_date,
    'messageSender' => $sender,
    'messageTo'=>$message_to,
    'Body'=>$body_data
    }
    }
    //It will print final result
    print_r($inboxMessage);
    function msg_body_recursive($part) {
    if($part->mimeType == 'text/html') {
    return ['html' => decodeBody($part->body->data)];
    } else if($part->mimeType == 'text/plain') {
    return ['plain' => decodeBody($part->body->data)];
    } else if($part->parts) {
    $return = [];
    foreach($part->parts as $sub_part) {
    $result = msg_body_recursive($sub_part);
    $return = array_merge($return, $result);
    if(array_key_exists('html', $return))
    break;
    }
    return $return;
    }
    return [];
    }
    function decodeBody($encoded) {
    $sanitizedData = strtr($encoded,'-_', '+/');
    return base64_decode($sanitizedData);
    }

Leave a Reply

Your email address will not be published. Required fields are marked *