Search code examples
phpgmailgoogle-oauthgmail-apigoogle-api-php-client

How to append thread messages while reply so that new user can see previous conversation in Gmail Api


I want to send reply message from Gmail Api and it is going fine and the message is threaded or appended to the reciever mailbox (A & B user). But If I add new CC user (we name as C) then the new User should see threaded messages which was previously communicated between A & B.

Please help me out if anybody know the solution

<?php
$client = getClient();
$gmail = new Google_Service_Gmail($client);
$message = new Google_Service_Gmail_Message();
$optParam = array();
$referenceId = '';
$thread = $gmail->users_threads->get('[email protected]', $threadId);
$optParam['threadId'] = '16c632fd24536690';
$threadMessages = $thread->getMessages($optParam);
$messageId = $threadMessages[0]->getId();
$subject = "Re: Thread mail test";
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->From = $from_email;
$mail->FromName = $from_name;
$mail->addCustomHeader('In-Reply-To', 
'<[email protected]>');
$mail->addCustomHeader('References', 
'<[email protected]>');
$mail->addAddress($to);
$mail->addcc($cc);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->preSend();
$mime = $mail->getSentMIMEMessage();
$raw = rtrim(strtr(base64_encode($mime), '+/', '-_'), '='); 
$message->setRaw($raw);
$message->setThreadId($threadId);
$response = $gmail->users_messages->send($userId, $message);
?>

Solution

  • Using Google Apps Script instead of Gmail API

    would allow you to use message.forward which would send all the messages of a thread. You could implement it by

    • List all thread messages with thread.getMessages()
    • Get the last thread message with threadMessages[threadMessages.length-1]
    • Forward the last thread message to desired recipients (A, B and C) with message.forward()

    If you want to stick to Gmail API, a workaround I can think of would imply to

    • get all thread messages
    • Get their raw contents
    • Append the raw contents of each thread message to the body of the message to send

    An example:

    function myFunction() {
    var myThread = GmailApp.getThreadById("PASTE HERE THE THREAD ID");
    var threadMessages = MyThread.getMessages();
    var lastMessage = threadMessages[threadMessages.length-1];
    lastMessage.forward("emailA", "emailB", "emailC");
    }