Sample code for 30+ languages & platforms
Java Requires Chilkat v11.0.0+

Reply to a message in its existing Gmail thread

See more GMail REST API Examples

Live send. Supply the Gmail ID of a received message and use an authorized From address. Fetch its raw MIME so Chilkat.Email can parse encoded headers and recipient addresses. Send a plain-text reply to Reply-To, falling back to From. The reply goes to the original sender or reply address.

The request supplies Gmail’s threadId and matching Subject. The MIME In-Reply-To contains the original RFC Message-ID. References preserves the conversation ancestry and appends that Message-ID. Select a message with a valid Message-ID and review its recipient before running this sending example. Authorize both gmail.readonly and gmail.send, or use gmail.modify as shown below.

Authorize the application with https://www.googleapis.com/auth/gmail.modify. The example reads the access token from gmail-token.json in a private working directory. Authorize a desktop application.

Google documentation

Chilkat Java Downloads

Java
import com.chilkatsoft.chilkat2.BinData;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Email;
import com.chilkatsoft.chilkat2.Http;
import com.chilkatsoft.chilkat2.HttpResponse;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.StringBuilder;

public class ChilkatExample {

    public static void main(String[] args) {
        boolean success = false;

        // Assumes Chilkat is unlocked. See Global Unlock Sample.

        JsonObject token = new JsonObject();
        try {
            token.loadFile("gmail-token.json");
        } catch (ChilkatException e) {
            System.out.println("Could not read gmail-token.json from the private working directory.");
            return;
        }

        if ((token.jsonTypeOf("access_token") != 1) || (token.stringOfEquals("access_token", "", true))) {
            System.out.println("An OAuth access token is required.");
            return;
        }

        Http http = new Http();
        http.setRequireSslCertVerify(true);
        http.setAuthToken(token.stringOf("access_token"));
        HttpResponse resp = new HttpResponse();
        JsonObject reply = new JsonObject();
        StringBuilder url = new StringBuilder();
        url.append("https://gmail.googleapis.com/gmail/v1/users/me/messages/");
        url.append("GMAIL_MESSAGE_ID");
        url.append("?format=raw");
        try {
            http.httpNoBody("GET", url.getAsString(), resp);
            success = true;
        } catch (ChilkatException e) {
            success = false;
        }
        if (resp.getStatusCode() == 0) {
            System.out.println("Gmail did not return an HTTP response.");
            return;
        }

        if ((!success) || ((resp.getStatusCode() < 200) || (resp.getStatusCode() >= 300))) {
            System.out.println("Gmail HTTP " + resp.getStatusCode());
            try {
                reply.load(resp.getBodyStr());
                success = true;
            } catch (ChilkatException e) {
                success = false;
            }
            if (success) {
                System.out.println(reply.stringOf("error.message"));
            }

            return;
        }

        try {
            reply.load(resp.getBodyStr());
        } catch (ChilkatException e) {
            System.out.println("Expected a Gmail JSON response.");
            return;
        }

        if ((reply.jsonTypeOf("threadId") != 1) || (reply.stringOfEquals("threadId", "", true))) {
            System.out.println("Expected threadId in the response.");
            return;
        }

        if ((reply.jsonTypeOf("raw") != 1) || (reply.stringOfEquals("raw", "", true))) {
            System.out.println("Expected raw in the response.");
            return;
        }

        String threadId = reply.stringOf("threadId");
        BinData originalMime = new BinData();
        try {
            reply.bytesOf("raw", "base64url", originalMime);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        Email original = new Email();
        try {
            original.setFromMimeBd(originalMime);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        String messageIdHeader = original.getHeaderField("Message-ID");
        if ((!original.getLastMethodSuccess()) || ("".equals(messageIdHeader))) {
            System.out.println("The original message needs a Message-ID for this threaded reply.");
            return;
        }

        Email email = new Email();
        email.setFrom("Sender <sender@example.com>");
        // Use the parsed Reply-To mailbox list when present, otherwise use From.
        String replyAddress = original.getReplyTo();
        if ("".equals(replyAddress)) {
            replyAddress = original.getFrom();
        }

        try {
            email.addMultipleTo(replyAddress);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        if (email.getNumTo() == 0) {
            System.out.println("The original message has no usable reply address.");
            return;
        }

        email.setSubject(original.getSubject());
        email.setCharset("utf-8");
        email.setBody("Thank you for your message.");
        email.addHeaderField("In-Reply-To", messageIdHeader);
        StringBuilder references = new StringBuilder();
        String previousReferences = original.getHeaderField("References");
        if ((original.getLastMethodSuccess()) && (!"".equals(previousReferences))) {
            references.append(previousReferences);
            references.append(" ");
        }

        references.append(messageIdHeader);
        email.addHeaderField("References", references.getAsString());
        BinData mime = new BinData();
        try {
            email.getMimeBd(mime);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        JsonObject request = new JsonObject();
        try {
            request.updateBd("raw", "base64url", mime);

            request.updateString("threadId", threadId);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        try {
            http.httpJson("POST", "https://gmail.googleapis.com/gmail/v1/users/me/messages/send", request, "application/json", resp);
            success = true;
        } catch (ChilkatException e) {
            success = false;
        }
        if (resp.getStatusCode() == 0) {
            System.out.println("Gmail did not return an HTTP response.");
            return;
        }

        if ((!success) || ((resp.getStatusCode() < 200) || (resp.getStatusCode() >= 300))) {
            System.out.println("Gmail HTTP " + resp.getStatusCode());
            try {
                reply.load(resp.getBodyStr());
                success = true;
            } catch (ChilkatException e) {
                success = false;
            }
            if (success) {
                System.out.println(reply.stringOf("error.message"));
            }

            return;
        }

        try {
            reply.load(resp.getBodyStr());
        } catch (ChilkatException e) {
            System.out.println("Expected a Gmail JSON response.");
            return;
        }

        if ((reply.jsonTypeOf("id") != 1) || (reply.stringOfEquals("id", "", true))) {
            System.out.println("Expected id in the response.");
            return;
        }

        System.out.println("Sent reply ID: " + reply.stringOf("id"));
        System.out.println("Thread ID: " + reply.stringOf("threadId"));
    }
}