๐ Source: get_email.php
<?php
session_name('INBOXZERO');
session_start();
header('Content-Type: application/json');
if (!isset($_SESSION['access_token'])) {
echo json_encode(['error' => 'Not authenticated']);
exit();
}
$input = json_decode(file_get_contents('php://input'), true);
$emailId = $input['email_id'] ?? '';
if (!$emailId) {
echo json_encode(['error' => 'No email ID provided']);
exit();
}
try {
require_once 'vendor/autoload.php';
$client = new Google\Client();
$client->setAccessToken($_SESSION['access_token']);
$service = new Google\Service\Gmail($client);
$message = $service->users_messages->get('me', $emailId, ['format' => 'full']);
$payload = $message->getPayload();
$decode = function($data) {
return base64_decode(strtr($data, '-_', '+/'));
};
$body = "";
// Cautฤ text/plain mai รฎntรขi
if ($payload->getParts()) {
foreach ($payload->getParts() as $part) {
if ($part->getMimeType() == 'text/plain' && $part->getBody() && $part->getBody()->getData()) {
$body = $decode($part->getBody()->getData());
break;
}
}
}
// Dacฤ nu gฤseศte text/plain, ia HTML ศi curฤศฤ
if (empty($body) && $payload->getBody() && $payload->getBody()->getData()) {
$body = $decode($payload->getBody()->getData());
}
if (empty($body) && $payload->getParts()) {
foreach ($payload->getParts() as $part) {
if ($part->getMimeType() == 'text/html' && $part->getBody() && $part->getBody()->getData()) {
$body = $decode($part->getBody()->getData());
break;
}
}
}
if (empty($body)) {
echo json_encode(['content' => '(No content in this email)']);
exit();
}
// Curฤศare HTML - eliminฤ tot ce nu e text
$body = preg_replace('/<style[^>]*>.*?<\/style>/is', '', $body);
$body = preg_replace('/<script[^>]*>.*?<\/script>/is', '', $body);
$body = preg_replace('/<head[^>]*>.*?<\/head>/is', '', $body);
$body = preg_replace('/<meta[^>]*>/i', '', $body);
$body = preg_replace('/<link[^>]*>/i', '', $body);
$body = preg_replace('/<title[^>]*>.*?<\/title>/is', '', $body);
// Extrage doar textul
$body = strip_tags($body);
$body = html_entity_decode($body, ENT_QUOTES | ENT_HTML5, 'UTF-8');
// Curฤศare text
$body = preg_replace('/\s+/', ' ', $body);
$body = trim($body);
// Eliminฤ URL-uri lungi
$body = preg_replace('/https?:\/\/[^\s]+/i', '[link]', $body);
// Eliminฤ footer
$body = preg_replace('/unsubscribe.*$/i', '', $body);
$body = preg_replace('/View in browser.*$/i', '', $body);
$body = preg_replace('/ยฉ.*$/i', '', $body);
// Dacฤ textul e prea scurt, รฎnseamnฤ cฤ e doar CSS
if (strlen($body) < 50) {
$body = "(No readable text content in this email)";
}
// Limiteazฤ lungimea
if (strlen($body) > 2000) {
$body = substr($body, 0, 2000) . "\n\n...(truncated)";
}
echo json_encode(['content' => $body]);
} catch (Exception $e) {
echo json_encode(['error' => $e->getMessage()]);
}
?>
โ Back