Create, Update, and Delete Contacts in Gmail using Java

Gmail is one of the commonly used online applications for sending and receiving emails. In addition, it allows working with calendars, contacts, chats, etc., and provides various other collaboration services. Recently, in an article, we have covered how to import contacts from a Gmail account. Today, you will learn how to create, update, and delete contacts in a Gmail account using Java.

Java API to Create, Update and Delete Gmail Contacts

To create and manipulate contacts in a Gmail account, we will use Aspose.Email for Java. It is a feature-rich API that lets you create and send emails and work with popular email clients. You can either download the API or install it using the following Maven configurations.

Repository:

<repository>
    <id>AsposeJavaAPI</id>
    <name>Aspose Java API</name>
    <url>http://repository.aspose.com/repo/</url>
</repository>

Dependency:

<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-email</artifactId>
    <version>22.3</version>
    <classifier>jdk16</classifier>
</dependency>

After installing the API, you need to create a project on the Google Developer Console, which will allow you to communicate with Gmail. To create one, you can follow this guide.

Now, create a helper class named GoogleOAuthHelper to take care of the authentication of a Gmail account. Also, create a class named OAuthUser to store user information. The following is the complete implementation of both classes.

public class OAuthUser {
String email;
String clientId;
String clientSecret;
String refreshToken;
}
view raw OAuthUser.java hosted with ❤ by GitHub
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.xml.bind.DatatypeConverter;
/**
* <p>
* Developers console https://console.developers.google.com/projectselector/apis/credentials?pli=1
* Documentation https://developers.google.com/identity/protocols/OAuth2InstalledApp
* </p>
*/
class GoogleOAuthHelper {
public static final String AUTHORIZATION_URL = "https://accounts.google.com/o/oauth2/v2/auth";
public static final String TOKEN_REQUEST_URL = "https://oauth2.googleapis.com/token";
public static final String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
public static final String REDIRECT_TYPE = "code";
public static final String SCOPE = "https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar" // Calendar
+ "+https%3A%2F%2Fwww.google.com%2Fm8%2Ffeeds%2F" // Contacts
+ "+https%3A%2F%2Fmail.google.com%2F"; // IMAP & SMTP
static String createCodeChalange() {
String verifierStr = UUID.randomUUID().toString() + "-" + UUID.randomUUID().toString();
System.out.println("Code Verifier: " + verifierStr);
MessageDigest digest;
try {
digest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new IllegalAccessError(e.getMessage());
}
byte[] hash = digest.digest(verifierStr.getBytes(StandardCharsets.UTF_8));
String base64Hash = DatatypeConverter.printBase64Binary(hash);
base64Hash = base64Hash.split("=")[0];
base64Hash = base64Hash.replace('+', '-').replace('/', '_');
return base64Hash;
}
static String getAuthorizationCodeUrl(OAuthUser acc) {
return getAuthorizationCodeUrl(acc, SCOPE, REDIRECT_URI, REDIRECT_TYPE);
}
static String getAuthorizationCodeUrl(OAuthUser acc, String scope, String redirectUri, String responseType) {
System.out.println("---------------------------------------------------------");
System.out.println("------------- OAuth 2.0 AuthorizationCodeUrl -------------");
System.out.println("---------------------------------------------------------");
System.out.println("Login: " + acc.email);
String codeChallenge = createCodeChalange();
String state = urlEncode(UUID.randomUUID().toString());
String approveUrl = AUTHORIZATION_URL + "?client_id=" + acc.clientId + "&redirect_uri=" + redirectUri + "&response_type=" + responseType + "&scope=" + scope
+ "&code_challenge=" + codeChallenge + "&code_challenge_method=S256&state=" + state;
System.out.println("Approve Url: " + approveUrl);
return approveUrl;
}
static String urlEncode(String value) {
try {
return URLEncoder.encode(value, StandardCharsets.UTF_8.toString());
} catch (UnsupportedEncodingException e) {
throw new IllegalAccessError(e.getMessage());
}
}
static String urlDecode(String value) {
try {
return URLDecoder.decode(value, StandardCharsets.UTF_8.toString());
} catch (UnsupportedEncodingException e) {
throw new IllegalAccessError(e.getMessage());
}
}
static String getAccessTokenByAuthCode(String authorizationCode, String codeVerifier, OAuthUser user) {
String encodedParameters = "client_id=" + urlEncode(user.clientId) + "&client_secret=" + urlEncode(user.clientSecret) + "&code=" + urlEncode(authorizationCode)
+ "&code_verifier=" + codeVerifier + "&redirect_uri=" + urlEncode(REDIRECT_URI) + "&grant_type=authorization_code";
System.out.println("---------------------------------------------------------");
System.out.println("------------- OAuth 2.0 AccessTokenByAuthCode -------------");
System.out.println("---------------------------------------------------------");
System.out.println("Authorization code: " + authorizationCode);
String result = "";
Map<String, String> token = geToken(encodedParameters);
for (String key : token.keySet()) {
System.out.println(key + ": " + token.get(key));
if (key.equals("refresh_token")) {
result = token.get(key);
}
}
System.out.println("---------------------------------------------------------");
return result;
}
static String getAccessTokenByRefreshToken(OAuthUser user) {
String encodedParameters = "client_id=" + urlEncode(user.clientId) + "&client_secret=" + urlEncode(user.clientSecret) + "&refresh_token=" + urlEncode(user.refreshToken)
+ "&grant_type=refresh_token";
System.out.println("---------------------------------------------------------");
System.out.println("----------- OAuth 2.0 AccessTokenByRefreshToken -----------");
System.out.println("---------------------------------------------------------");
System.out.println("Login: " + user.email);
String result = "";
Map<String, String> token = geToken(encodedParameters);
for (String key : token.keySet()) {
System.out.println(key + ": " + token.get(key));
if (key.equals("access_token")) {
result = token.get(key);
}
}
System.out.println("---------------------------------------------------------");
return result;
}
static Map<String, String> geToken(String encodedParameters) {
try {
HttpURLConnection connection = (HttpURLConnection) new URL(TOKEN_REQUEST_URL).openConnection();
connection.setRequestMethod("POST");
byte[] requestData = encodedParameters.getBytes(StandardCharsets.UTF_8);
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" + requestData.length);
final OutputStream st = connection.getOutputStream();
try {
st.write(requestData, 0, requestData.length);
} finally {
st.flush();
st.close();
}
connection.connect();
if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST) {
throw new IllegalAccessError("Operation failed: " + connection.getResponseCode() + "/" + connection.getResponseMessage() + "\r\nDetails:\r\n{2}"
+ readInputStream(connection.getErrorStream()));
}
String responseText = readInputStream(connection.getInputStream());
Map<String, String> result = new HashMap<String, String>();
System.out.println(responseText);
String[] strs = responseText.replace("{", "").replace("}", "").replace("\"", "").replace("\r", "").replace("\n", "").split(",");
for (String sPair : strs) {
String[] pair = sPair.split(":");
String name = pair[0].trim().toLowerCase();
String value = urlDecode(pair[1].trim());
result.put(name, value);
}
return result;
} catch (IOException e) {
throw new IllegalAccessError(e.getMessage());
}
}
static String readInputStream(InputStream is) {
if (is == null)
return "";
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder result = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
// ignore
}
return result.toString();
}
}

Create a Contact on Gmail in Java

The following are the steps to create a contact on Gmail in Java.

The following code sample shows how to create a contact on Gmail in Java.

OAuthUser user = new OAuthUser();
// Set clientId, clientSecret and email
user.clientId = "<<clientID>>";
user.clientSecret = "<<clientSecret>>";
user.email = "<<email>>";
// You have to retrieve AuthorizationCode manually with generated AuthorizationCodeUrl
// Set authorizationCode
String authorizationCode = "<<authCode>>";
// Copy Code Verifier from the previous step output
// Set codeVerifier
String codeVerifier = "<<codeVerifier>>";
// Get Refresh Token
String refreshToken = GoogleOAuthHelper.getAccessTokenByAuthCode(authorizationCode, codeVerifier, user);
user.refreshToken = refreshToken;
// Get Access Token
String accessToken = GoogleOAuthHelper.getAccessTokenByRefreshToken(user);
// Use Access Token in API
IGmailClient client = GmailClient.getInstance(accessToken, user.email);
// Create a Contact
Contact contact = new Contact();
contact.setPrefix("Prefix");
contact.setGivenName("GivenName");
contact.setSurname("Surname");
contact.setMiddleName("MiddleName");
contact.setDisplayName("DisplayName");
contact.setSuffix("Suffix");
contact.setJobTitle("JobTitle");
contact.setDepartmentName("DepartmentName");
contact.setCompanyName("CompanyName");
contact.setProfession("Profession");
contact.setNotes("Notes");
// Set postal address
PostalAddress address = new PostalAddress();
address.setCategory(PostalAddressCategory.getWork());
address.setAddress("Address");
address.setStreet("Street");
address.setPostOfficeBox("PostOfficeBox");
address.setCity("City");
address.setStateOrProvince("StateOrProvince");
address.setPostalCode("PostalCode");
address.setCountry("Country");
contact.getPhysicalAddresses().add(address);
// Set phone number
PhoneNumber pnWork = new PhoneNumber();
pnWork.setNumber("323423423423");
pnWork.setCategory(PhoneNumberCategory.getWork());
contact.getPhoneNumbers().add(pnWork);
PhoneNumber pnHome = new PhoneNumber();
pnHome.setNumber("323423423423");
pnHome.setCategory(PhoneNumberCategory.getHome());
contact.getPhoneNumbers().add(pnHome);
PhoneNumber pnMobile = new PhoneNumber();
pnMobile.setNumber("323423423423");
pnMobile.setCategory(PhoneNumberCategory.getMobile());
contact.getPhoneNumbers().add(pnMobile);
// Set other details
contact.getUrls().setBlog("Blog.com");
contact.getUrls().setBusinessHomePage("BusinessHomePage.com");
contact.getUrls().setHomePage("HomePage.com");
contact.getUrls().setProfile("Profile.com");
contact.getEvents().setBirthday(new Date());
contact.getEvents().setAnniversary(new Date());
contact.getInstantMessengers().setAIM("AIM");
contact.getInstantMessengers().setGoogleTalk("GoogleTalk");
contact.getInstantMessengers().setICQ("ICQ");
contact.getInstantMessengers().setJabber("Jabber");
contact.getInstantMessengers().setMSN("MSN");
contact.getInstantMessengers().setQQ("QQ");
contact.getInstantMessengers().setSkype("Skype");
contact.getInstantMessengers().setYahoo("Yahoo");
contact.getAssociatedPersons().setSpouse("Spouse");
contact.getAssociatedPersons().setSister("Sister");
contact.getAssociatedPersons().setRelative("Relative");
contact.getAssociatedPersons().setReferredBy("ReferredBy");
contact.getAssociatedPersons().setPartner("Partner");
contact.getAssociatedPersons().setParent("Parent");
contact.getAssociatedPersons().setMother("Mother");
contact.getAssociatedPersons().setManager("Manager");
// Set email address
EmailAddress eAddress = new EmailAddress();
eAddress.setAddress("email@gmail.com");
contact.getEmailAddresses().add(eAddress);
// Create contact
String contactUri = client.createContact(contact);

Update a Contact on Gmail in Java

You can also update the details of a Gmail contact after accessing it. The following are the steps to update a contact in a Gmail account in Java.

The following code sample shows how to update a contact in Gmail in Java.

OAuthUser user = new OAuthUser();
// Set clientId, clientSecret and email
user.clientId = "<<clientID>>";
user.clientSecret = "<<clientSecret>>";
user.email = "<<email>>";
// You have to retrieve AuthorizationCode manually with generated AuthorizationCodeUrl
// Set authorizationCode
String authorizationCode = "<<authCode>>";
// Copy Code Verifier from the previous step output
// Set codeVerifier
String codeVerifier = "<<codeVerifier>>";
// Get Refresh Token
String refreshToken = GoogleOAuthHelper.getAccessTokenByAuthCode(authorizationCode, codeVerifier, user);
user.refreshToken = refreshToken;
// Get Access Token
String accessToken = GoogleOAuthHelper.getAccessTokenByRefreshToken(user);
// Use Access Token in API
IGmailClient client = GmailClient.getInstance(accessToken, user.email);
// Get all contacts
Contact[] contacts = client.getAllContacts();
// Fetch required one
Contact contact = contacts[0];
contact.setJobTitle("Manager IT");
contact.setDepartmentName("Customer Support");
contact.setCompanyName("Aspose");
contact.setProfession("Software Developer");
// Update contact
client.updateContact(contact);

Delete a Contact on Gmail in Java

Finally, let’s see how to delete a Gmail contact using Java. The following are the steps to perform this operation.

The following code sample shows how to delete a contact on Gmail in Java.

OAuthUser user = new OAuthUser();
// Set clientId, clientSecret and email
user.clientId = "<<clientID>>";
user.clientSecret = "<<clientSecret>>";
user.email = "<<email>>";
// You have to retrieve AuthorizationCode manually with generated AuthorizationCodeUrl
// Set authorizationCode
String authorizationCode = "<<authCode>>";
// Copy Code Verifier from the previous step output
// Set codeVerifier
String codeVerifier = "<<codeVerifier>>";
// Get Refresh Token
String refreshToken = GoogleOAuthHelper.getAccessTokenByAuthCode(authorizationCode, codeVerifier, user);
user.refreshToken = refreshToken;
// Get Access Token
String accessToken = GoogleOAuthHelper.getAccessTokenByRefreshToken(user);
// Use Access Token in API
IGmailClient client = GmailClient.getInstance(accessToken, user.email);
// Get all contacts
Contact[] contacts = client.getAllContacts();
// Fetch required one
Contact contact = contacts[0];
// Delete contact
client.deleteContact(contact.getId().getGoogleId());

Get a Free API License

You can use Aspose.Email for Java without evaluation limitations using a free temporary license.

Conclusion

In this article, you have learned how to create and update contacts in a Gmail account in Java. Furthermore, you have seen how to delete a Gmail contact programmatically. Besides, you can visit the documentation to explore other features of Aspose.Email for Java. In case you would have any questions, you can post to our forum.

See Also