0

Okay so i have been playing around with PHPmailer for a while now and i have 1 last issue to resolve till i have finished my project

I use phpMailer to receive emails and they are coming out encoded. I have tried to use echo mb_detect_encoding($str, "auto"); to detect encoding and it won't detect any encoding.

I have tried to utf8_decode() the mail contents (taken from the database) and it still comes out with UTF-8 encoding. As there is mixed base64, i also need a way to detect if there is base64, and decode that too.

$emailContentsVar = $row['email_message'];
   if ( base64_decode($emailContentsVar, true) == true){
    echo base64_decode($emailContentsVar);
   } else {
    echo "<div id='Emails' style='background-color: #F26D21; color: white;'>" . utf8_decode($emailContentsVar) . "</div><br>";

I have tried using UTF-8 headers too and that's made no difference. Ive tried to just decode the emails instantly but it will then result in non-encoded emails to just come out in unreadable letters.

This is the code i am using to store the data (my code is messy so sorry for that. I have a very messy mind and my code reflects that). https://pastebin.com/Mq9AUBzp

<?php header('Content-Type: text/html; charset=utf-8'); ?>
<html>
  <head>
    <meta name="google" content="notranslate">
    <meta charset="UTF-8">
    <!--[if !mso]><!-- -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!--<![endif]-->
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <?php 
//echo ' <meta http-equiv="refresh" content="0;url=../mail.php?emailUpdate=' . $emailsCount . '" />';
include("../assets/sqlconfig.php");
$emailsCount = 0;?>
  </head>
  <body>
    
  <?php
  error_reporting(0);
  echo '<a href="../mail.php">Back</a>';
  // Multiple email account
  $emails = array(
   array(
    'no' => '1', #####',
    'host' => '######',
    'username' => '#######',
    'password' => '#######'
   )
   // bla bla bla ...
  );
  foreach ($emails as $email) {
   $read = imap_open($email['host'], $email['username'], $email['password']) or die('<div class="alert alert-danger alert-dismissable">Cannot connect to ###### mailbox: ' . imap_last_error() . '</div>');
   $array = imap_search($read, 'ALL');
   if ($array) {
    $html = '';
    rsort($array);
    $html .= '<div class="panel panel-default">
   <div class="panel-heading">
   ' . $email['label'] . '
   </div>
   <div class="panel-body">
   <div class="panel-group" id="accordion">';
    foreach ($array as $result) {
     $overview         = imap_fetch_overview($read, $result, 0);
     //    $conn = new mysqli($servername, $username, $password, $dbname);
     $conn             = new mysqli($servername, $username, $password, $dbname);
     $message          = imap_body($read, $result, 0);
     $reply            = imap_headerinfo($read, $result, 0);
     $input_number     = mysqli_real_escape_string($conn, $email['no'] . $result);
     $input_subject    = mysqli_real_escape_string($conn, substr(strip_tags($overview[0]->subject), 0, 50));
     $input_from       = mysqli_real_escape_string($conn, $overview[0]->from);
     $input_from_email = mysqli_real_escape_string($conn, $reply->from[0]->mailbox . '@' . $reply->from[0]->host);
     $input_email      = mysqli_real_escape_string($conn, $message);
     $input_date       = mysqli_real_escape_string($conn, $overview[0]->date);
     // Check email exsistance
     if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
     }
     $sql    = "SELECT * FROM `mail` WHERE `email_number` = '$input_number'";
     $result = $conn->query($sql);
     if ($result->num_rows > 0) {
      //echo "Email There<br>" . $input_number . "<br>";
     } else {
      $emailsCount++;
      //ADDING EMAILS TO DB
      $conn = new mysqli($servername, $username, $password, $dbname);
      if ($conn->connect_error) {
       die("Connection failed: " . $conn->connect_error);
      }
      $sql = "INSERT INTO `mail` (`id`, `email_number`, `email_subject`, `email_message`, `email_from`, `email_from_email`, `email_date`, `email_read_status`) VALUES (NULL, '$input_number', '$input_subject', '$input_email', '$input_from', '$input_from_email', '$input_date', 'Unread');";
      echo $input_subject . "<br>";
      if ($conn->query($sql) === TRUE) {
       //    echo "New record created successfully<br>";
      } else {
       //echo "Error: " . $sql . "<br>" . $conn->error;
      }
      $conn->close();
      //ADDING EMAILS TO DB END
     }
     $conn->close();
     // Check email exsistance END
     /*    $html.= '    <div class="panel panel-default">
     <div style="color: red;" class="panel-heading">
     <h4 class="panel-title">
     <a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#'.$email['no'].$result.'">
     <span class="subject">'.substr(strip_tags($overview[0]->subject),0,50).'.. </span>
     <span class="from">'.$overview[0]->from.'</span>
     <span class="date">on '.$overview[0]->date.'</span>
     </a>
     </h4>
     </div>
     <div id="'.$email['no'].$result.'" class="panel-collapse collapse">
     <div class="panel-body">
     <pre>'.$message.'<hr>From: '.$reply->from[0]->mailbox.'@'.$reply->from[0]->host.'</pre>
     </div>
     </div>
     </div>';     */
    }
    $html .= '</div>
   </div>
   </div>';
    echo $html;
   }
   imap_close($read);
   echo '<script>window.location.href="../mail.php?emailUpdate=' . $emailsCount . '";</script>';
   //echo "<center>" . $emailsCount . " New emails</center>";
   //echo $emailsCount;
  }
  ?>





    <!-- Javascript -->
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js">
    </script>
  </body>
</html>

This is the code i use to then read from the SQL https://pastebin.com/1HsEtu8s

<?php header('Content-Type: text/html; charset=utf-8'); ?>
<html>
  <head>
    <meta name="google" content="notranslate">
    <meta charset="UTF-8">
    <!--[if !mso]><!-- -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!--<![endif]-->
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
    <!-- Custom style -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/custom.css">
    <style>
      pre {
        white-space: pre;
        white-space: pre-wrap;
        word-wrap: break-word;
      }
    </style>
    <?php include("assets/nav.php"); 
include("assets/sqlconfig.php");?>
  </head>
  <body>
    <div class="alert alert-info alert-dismissable">
      <div style="background-color: #A3B86C; color: white; font-size: 20px;">
        <center>
          <a href="functions/mailLoad.php">Click here to load Mail 
          </a>
        </center>
      </div>
      <div>
        <?php
   include("../assets/sqlconfig.php");
   if(isset($_GET['emailUpdate'])){
    echo "<center>" . $_GET['emailUpdate'] . " New emails</center>";
   }
   $conn = new mysqli($servername, $username, $password, $dbname);
   if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
   } 
   $sql = "SELECT * FROM `mail` ORDER BY `email_number` DESC";
   $result = $conn->query($sql);
   if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
    $emailContentsVar = $row['email_message'];
   if ( base64_decode($emailContentsVar, true) == true){
    echo base64_decode($emailContentsVar);
   } else {
    echo "<div id='Emails' style='background-color: #F26D21; color: white;'>" . $emailContentsVar . "</div><br>"; 
   }
  }
  } else {
   echo "0 results";
  }
   $conn->close();
   exit;
   ?>
        <script>
          $(document).ready(function(){
            var ajaxurl = 'functions/mailLoad.php',
                data =  {
                  'action': 'load'};
            $.post(ajaxurl, data, function (response) {
              alert(response);
            }
                  );
          }
                           );
          <!-- Javascript -->
            <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
              <script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script>
                <script>
                // $(".panel-heading").click(function(){
                // Holds the product ID of the clicked element
                // });
        </script>
        </body>
      </html>

Finally this is what the emails are coming out like and how they are stored in mySQL

Emails Base64 with normal emails

Emails in UTF-8 encoding + some that use our application process that seems to just be in plain HTML

How it is stored in our DB

Sorry this is all a bit messy. This is the first time ive ever posted on stackoverflow and having a bit of a learning curve lol.

Any help with this would be awesome :)

EDIT:

Okay so

if ( base64_decode($emailContentsVar, true) == true){
   echo base64_decode($emailContentsVar);
   }

can decode this Base64 email but cant decode this base64 email. The main issue seems to be how many variariations of encodings there is within the emails and it seems like there not just pure encoding. They seem to be mixed encoding, plain text and html

EDIT 2:

Okay so getting a little closer now!

   quoted_printable_decode($emailContentsVar)
Has decoded a bit more of 1 of the emails. It now looks like this: Decoded email but it as decoded it in a very strange way. Its decoded my sent part, but not the recived part of the reply. I have been trying all sorts of decoding methods but nothing will remove the main part of the encoding. I was going to just use regex, but every email is slightly diffrent, depending the device the email was sent from. Also still cant decode the large image base64 email.
  • We are always glad to help and support new coders but you need to help yourself first. :-) [After doing more research](https://meta.stackoverflow.com/q/261592/1011527) if you have a problem post what you've tried with a clear explanation of what isn't working and provide a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). Read [How to Ask](http://stackoverflow.com/help/how-to-ask) a good question. Be sure to [take the tour](http://stackoverflow.com/tour) and read [this](https://meta.stackoverflow.com/q/347937/1011527). – Dave Aug 05 '18 at 12:43
  • You need to come up with a minimal example that shows the problem and add it to your post. People aren't going to go off to another site to look at your code. – Dave Aug 05 '18 at 12:43
  • Possible duplicate of [PHPMailer character encoding issues](https://stackoverflow.com/questions/2491475/phpmailer-character-encoding-issues) – Dave Aug 05 '18 at 12:44
  • @Dave I have repaired the code snippets so its all on here now without going onto Pastebin. As for making a small example, I'm not to sure where the issue could possibly be so i had to post it all. Ie I'm not sure if its a header issue, a SQL issue, a php echoing issue or if its just down to the way im reading the emails. Im very new to PHPmailer and to be honest im so confused by it all, i had to chop parts from other code and add it to mine so its a bit of a frankinstine code haha. I have had a look at other posts but they all seem to be using frameworks or more complex code then me – Modz Marvin Aug 05 '18 at 13:00

1 Answers1

0

I had the same problem as you before ! If you want to decode your message without HTML, I suggest you use the function html_entity_decode that's what I use for HTML mails.

You will see the result ! (I am a beginner in PHP so please excuse me if I said a stupidity, I'm just trying to help)

Fl0 42
  • 21
  • 2
  • Unfortunately, it didn't manage to decode any of the emails :(. It has helped me realize my base64 detection method i have in there is decoding one email through so not a complete loss hehe. – Modz Marvin Aug 05 '18 at 13:22