diff --git a/include/class.thread.php b/include/class.thread.php
index 8f108d70503ef5fb4f65a667b02c5da964e4da2f..05642a322d730d2daaa0b71c5da6a0b6183bd112 100644
--- a/include/class.thread.php
+++ b/include/class.thread.php
@@ -674,11 +674,16 @@ Class ThreadEntry {
         }
 
         // Search for ticket by the [#123456] in the subject line
+        // This is the last resort -  emails must match to avoid message
+        // injection by third-party.
         $subject = $mailinfo['subject'];
         $match = array();
-        if ($subject && preg_match("/\[#([0-9]{1,10})\]/", $subject, $match))
+        if ($subject && $mailinfo['email']
+                && preg_match("/\[#([0-9]{1,10})\]/", $subject, $match)
+                && ($tid = Ticket::getIdByExtId((int)$match[1], $mailinfo['email']))
+                )
             // Return last message for the thread
-            return Message::lastByExtTicketId((int)$match[1]);
+            return Message::lastByTicketId($tid);
 
         return null;
     }
@@ -783,15 +788,16 @@ class Message extends ThreadEntry {
                 )?$m:null;
     }
 
-    function lastByExtTicketId($ticketId) {
-        $sql = 'SELECT thread.id FROM '.TICKET_THREAD_TABLE
-            .' thread JOIN '.TICKET_TABLE.' ticket ON (ticket.ticket_id = thread.ticket_id)
-                WHERE thread_type=\'M\' AND ticket.ticketID = '.db_input($ticketId)
+    function lastByTicketId($ticketId) {
+
+        $sql=' SELECT thread.id FROM '.TICKET_THREAD_TABLE.' thread '
+            .' WHERE thread_type=\'M\' AND thread.ticket_id = '.db_input($ticketId)
             .' ORDER BY thread.id DESC LIMIT 1';
-        if (($res = db_query($sql)) && (list($id) = db_fetch_row($res)))
+
+        if (($res = db_query($sql)) && ($id = db_result($res)))
             return Message::lookup($id);
-        else
-            return null;
+
+        return null;
     }
 }
 
diff --git a/include/class.ticket.php b/include/class.ticket.php
index 85b7e3b3820d447ba02c810fdbf975e899887022..294291f65cd079ae43e756bdeca738abc3011662 100644
--- a/include/class.ticket.php
+++ b/include/class.ticket.php
@@ -471,7 +471,11 @@ class Ticket {
     }
 
     function getLastMessage() {
-        return Message::lookup($this->getLastMsgId(), $this->getId());
+
+        if($this->getLastMsgId())
+            return Message::lookup($this->getLastMsgId(), $this->getId());
+
+        return Message::lastByTicketId($this->getId());
     }
 
     function getThread() {