Working with Gmail Using the Gmail Service Client in Java
GmailClient from the com.aspose.email.services.google.mail.client package works with messages, threads, labels and drafts through the Gmail API. The client connects over HTTP. To learn how to select an HTTP library, see HTTP Clients for Mail Services.
com.aspose.email package has a class with the same name, which is described in Programming with Gmail. Use explicit imports to select the class you need.
Connecting to Gmail
The Google clients authenticate with OAuth 2.0. GoogleOAuthTokenProvider exchanges a refresh token for access tokens and renews them when they are about to expire. Create the client ID, the client secret and the refresh token in your Google Cloud project, and grant the refresh token the scopes of the APIs that you call.
The following code sample creates a client and lists the messages of the authenticated user. Other code samples on this page use the gmail variable created here.
import com.aspose.email.services.google.base.auth.GoogleOAuthTokenProvider;
import com.aspose.email.services.google.mail.client.GmailClient;
import com.aspose.email.services.google.mail.model.GmailMessage;
GoogleOAuthTokenProvider tokens = new GoogleOAuthTokenProvider("client-id", "client-secret", "refresh-token");
try (GmailClient gmail = GmailClient.builder().tokenProvider(tokens).build()) {
for (GmailMessage message : gmail.me().messages().list()) {
System.out.println(message.getId());
}
}
The same token provider can be shared with CalendarClient and PeopleClient.
The me method selects the authenticated user. To access another mailbox that your credentials allow, call users with its address, for example gmail.users("user@example.com").
Listing and Searching Messages
The list method returns only the identifiers of messages, so getSubject and getFrom return null for these objects. To read a message, get it by its identifier as shown in the next section.
To search for messages, pass a query in the Gmail search syntax. To read the results page by page, use listPaged:
import com.aspose.email.services.google.mail.api.GmailPagedResult;
import com.aspose.email.services.google.mail.model.GmailMessage;
String pageToken = null;
do {
GmailPagedResult<GmailMessage> page =
gmail.me().messages().listPaged("is:unread from:user@example.com", 50, pageToken);
for (GmailMessage message : page.getItems()) {
System.out.println(message.getId());
}
pageToken = page.getNextPageToken();
} while (pageToken != null);
Reading a Message
To get the headers and the structure of a message, call get on the client of the message:
import com.aspose.email.services.google.mail.model.GmailMessage;
import com.aspose.email.services.google.mail.model.GmailMessagePart;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
GmailMessage message = gmail.me().messages("message-id").get();
System.out.println(message.getSubject() + ", from " + message.getFrom() + ", unread: " + message.isUnread());
for (GmailMessagePart part : message.getPayload().getParts()) {
if ("text/plain".equals(part.getMimeType())) {
byte[] text = Base64.getUrlDecoder().decode(part.getBodyData());
System.out.println(new String(text, StandardCharsets.UTF_8));
}
}
The getBodyData method returns the content in the Base64URL encoding, so decode it with Base64.getUrlDecoder.
To work with a complete message and its attachments, get it in the MIME format with getMime, and then load it into a MailMessage:
import com.aspose.email.Attachment;
import com.aspose.email.MailMessage;
import java.io.ByteArrayInputStream;
byte[] mime = gmail.me().messages("message-id").getMime();
MailMessage message = MailMessage.load(new ByteArrayInputStream(mime));
System.out.println(message.getSubject());
for (Attachment attachment : message.getAttachments()) {
System.out.println(attachment.getName());
}
Sending a Message
The send method accepts a message in the MIME format. The following code sample creates a MailMessage, saves it as EML and sends the result. A new MailMessage is marked as a draft, so the code sample clears this flag with isDraft(false). Otherwise, the saved message has the X-Unsent: 1 header, which some mail clients use to open a message as a draft.
import com.aspose.email.MailMessage;
import com.aspose.email.SaveOptions;
import com.aspose.email.services.google.mail.model.GmailMessage;
import java.io.ByteArrayOutputStream;
MailMessage message = new MailMessage("user@example.com", "to@example.com", "Weekly report", "The report is ready.");
message.isDraft(false);
ByteArrayOutputStream mime = new ByteArrayOutputStream();
message.save(mime, SaveOptions.getDefaultEml());
GmailMessage sent = gmail.me().messages().send(mime.toByteArray());
System.out.println(sent.getId());
Working with Labels
Use labels to list and create labels. To add labels to a message or remove them from it, call modify with the identifiers of the labels. The GmailMessage class has constants for system labels such as LABEL_UNREAD.
import com.aspose.email.services.google.mail.model.GmailLabel;
import com.aspose.email.services.google.mail.model.GmailMessage;
for (GmailLabel label : gmail.me().labels().list()) {
System.out.println(label.getId() + ": " + label.getName());
}
GmailLabel reports = gmail.me().labels().create("Reports");
gmail.me().messages("message-id").modify(
new String[]{reports.getId()},
new String[]{GmailMessage.LABEL_UNREAD});
Working with Threads
A thread groups related messages. The list method returns the identifiers and the snippets of threads, and get returns a thread with its messages:
import com.aspose.email.services.google.mail.model.GmailMessage;
import com.aspose.email.services.google.mail.model.GmailThread;
for (GmailThread thread : gmail.me().threads().list("subject:report")) {
GmailThread full = gmail.me().threads(thread.getId()).get();
for (GmailMessage message : full.getMessages()) {
System.out.println(message.getSubject());
}
}
Working with Drafts
To create a draft, pass a message in the MIME format to create. To send the draft, call send with its identifier:
import com.aspose.email.services.google.mail.model.GmailDraft;
import com.aspose.email.services.google.mail.model.GmailMessage;
import java.nio.charset.StandardCharsets;
byte[] mime = "From: user@example.com\r\nTo: to@example.com\r\nSubject: Weekly report\r\n\r\nThe report is ready."
.getBytes(StandardCharsets.UTF_8);
GmailDraft draft = gmail.me().drafts().create(mime);
GmailMessage sent = gmail.me().drafts().send(draft.getId());
System.out.println(sent.getId());
Deleting a Message
The trash method moves a message to the trash, and untrash restores it. The delete method removes a message permanently:
gmail.me().messages("message-id").trash();
gmail.me().messages("message-id").untrash();
gmail.me().messages("message-id").delete();
Handling Errors
When the Gmail API returns an error status, the client throws HttpClientException, which contains the status and the response body. If the token provider cannot get an access token, the client throws java.io.IOException, which is also the base class of HttpClientException.
import com.aspose.ext.http.HttpClientException;
try {
gmail.me().messages("unknown-id").get();
} catch (HttpClientException e) {
System.out.println(e.getStatusCode() + ": " + e.getResponseBody());
}