Issues with rendering html emails

66 Views Asked by At

I'm trying to build a small PHP app. In the section of the app, users can view emails from their inbox. The problem I have is the emails are not rendered correctly.

So it renders the emails but I end up seeing the css and basic html code of emails. Images are not also being loaded. Here is my code

<?php

use Mustache_Engine;
use Mustache_Loader_FilesystemLoader;
require_once '/home/dashboard/vendor/autoload.php';

$server = '{test severy:993/imap/ssl}INBOX';
$username = 'XXX@gmail';
$password = 'password';


$mailbox = imap_open($server, $username, $password) or die('Cannot connect to the server: ' . imap_last_error());


$loader = new Mustache_Loader_FilesystemLoader('/home/dashboard');
$mustache = new Mustache_Engine(['loader' => $loader]);

$totalMessages = imap_num_msg($mailbox);

for ($i = 1; $i <= $totalMessages; $i++) {
    $header = imap_headerinfo($mailbox, $i);
    $messageBody = imap_fetchbody($mailbox, $i, 1);
    $structure = imap_fetchstructure($mailbox, $i);
    $isHTML = ($structure->type == 2 && $structure->subtype == 'HTML');

    
    $cleanedContent = strip_tags($messageBody, '<p><a><strong><em><u><br><img>');

    echo '<strong>From:</strong> ' . $header->fromaddress . '<br>';
    echo '<strong>Subject:</strong> ' . htmlspecialchars($header->subject) . '<br>';
    echo '<strong>Date:</strong> ' . date('Y-m-d H:i:s', strtotime($header->date)) . '<br>';

    echo '<strong>Message:</strong><br>';
    if ($isHTML) {
       
        $template = $mustache->loadTemplate('email-template.mustache');
        $renderedContent = $template->render([
            'subject' => htmlspecialchars($header->subject),
            'messageBody' => '<style>' . $cleanedContent . '</style>',
        ]);

        echo $renderedContent;
    } else {
        // Plain text content
        echo nl2br(htmlspecialchars($cleanedContent));
    }

    echo '<hr>';
}

imap_close($mailbox);
?>

Any help will be appreciated. I had to remove commentin the code so whole text can get in

Here are the images:

Image 1

Image2

Image 3

I have tried to use template like Mustache_Engine yet the emails are not rendering fine.

0

There are 0 best solutions below