zee
zee

Reputation: 502

How to use batch requests for Gmail Send API

I am currently sending more than one Emails at a time using Gmail API. I am doing this sequentially:

  1. Send an Email via GmailAPI
  2. Wait for response from GmailAPI.
  3. When response is received, update the Record with ThreadID returned by GmailAPI.
  4. Repeat steps 1-3 for other emails.

I was reading about batching your sendEmail API requests,so that we make one call to API and handle the responses. Although i am able to batch my all request and send it,

I am not sure about how to handle Responses. If i have 30 Send Email Requests in the batch request, when the response is received for the batch, how do i figure out which response is for which Email?

Here is my Implementation

BatchRequest batch  = gmailService.batch();
gmailService.users().messages().send("me", message).queue(batch, callback);
batch.execute();

    final List<Message> messages = new ArrayList<Message>();
        JsonBatchCallback<Message> callback = new JsonBatchCallback<Message>() {
            public void onSuccess(Message message, HttpHeaders  responseHeaders) {
                System.out.println("MessageThreadID:"+ message.getThreadId());
                System.out.println("MessageID:"+ message.getId());
                synchronized (messages) {
                    messages.add(message);  
                }
            }

            @Override
            public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders)
                    throws IOException {
            }
        };

Upvotes: 0

Views: 1425

Answers (1)

Danee
Danee

Reputation: 322

I am not sure about how to handle Responses. If i have 30 Send Email Requests in the batch request, when the response is received for the batch, how do i figure out which response is for which Email?

According to this Batch Request Response document:

Response to a batch request

The server's response is a single standard HTTP response with a multipart/mixed content type; each part is the response to one of the requests in the batched request, in the same order as the requests.

Like the parts in the request, each response part contains a complete HTTP response, including a status code, headers, and body. And like the parts in the request, each response part is preceded by a Content-Type header that marks the beginning of the part.

You could get the the complete HTTP response, its status code, its headers, and its body in the order to which you made the request. So response one is for 1st request, response 2 is for 2nd request and so forth. In this way, you might figure the response for which Email.

Upvotes: 1

Related Questions