You probably solved this by now, but I had similar issues and found this thread while looking for a solution, so I wanted to share the approach I used in case someone else needs it.
Based on Gmail's API specification
1.The requested threadId must be specified on the Message or Draft.Message you supply with your request.
2.The References and In-Reply-To headers must be set in compliance with the RFC 2822 standard.
3.The Subject headers must match.
The number 2 complicated things for me, because I tried to set the References and In-Reply-To headers manually. My idea was to get them from the last message in the same thread, but the API didn't return those headers and what I set was apparently inaccurate. Then, following this thread MIME Headers Not Making it Through Gmail API, I removed all additional headers and set only the threadId and a matching subject.
I used PHPMailer library for formatting the mime string, instead of doing it manually (it decreases the possibility of mistakes). With composer, you just need to add "phpmailer/phpmailer": "~5.2" in the require section of your composer.json.
Here's my solution:
$thread = $gmail->users_threads->get($user_id,$threadId);
if($thread) {
$opt_param['threadId'] = $threadId;
$thread_messages = $thread->getMessages($opt_param);
if($thread_messages) {
$messageId = $thread_messages[0]->getId();
$messageDetails = $gmail->users_messages->get($messageId);
// get the subject here from the headers of $messageDetails. You will use it below as $subject.
}
}
$message = new Google_Service_Gmail_Message();
$mail = new PHPMailer();
$mail->From = 'YOUR_EMAIL'; // I tried with 'me' here, but PHPMailer doesn't consider it valid, so it can either be the email or userId
$mail->FromName = 'YOUR_NAME';
$mail->addAddress('RECIPIENT_EMAIL'); // Make sure this is the same as the email in the message you reply to
$mail->Subject = $subject; // the subject from $messageDetails from above
$mail->Body = $body;
$mail->preSend();
$mime = $mail->getSentMIMEMessage();
$raw = rtrim(strtr(base64_encode($mime), '+/', '-_'), '='); // web safe base64 encode
$message->setRaw($raw); // You set the thread id to your message object now, separately from the other headers
$message->setThreadId($threadId);
$gmail->users_messages->send($user_id, $message);
Variables used above:
$gmail - your instance of Google_Service_Gmail;
$user_id - the id of the authenticated user (can be 'me' for the current logged in user);
$threadId - the thread under which you want to send your email
Hope this is helpful.