When replying to a user_private_message email originating from a group PM that does not have a reply key (e.g. when replying directly to the group’s SMTP address), we were mistakenly linking the new post created from the reply to the OP and the user who created the topic, based on the first IncomingEmail message ID in the topic, rather than using the correct reply to user and post number that the user actually replied to.
We now use the In-Reply-To header to look up the corresponding EmailLog record when the user who replied was sent a user_private_message email, and use the post from that as the reply_to_user/post.
This also removes superfluous filtering of incoming_email records. After already filtering by message_id and then addressed_to_user (which only returns incoming emails where the to, from, or cc address includes any of the user’s emails), we were filtering again but in the ruby code for the exact same conditions. After removing this all existing tests still pass.