Created
January 18, 2013 11:57
-
-
Save raphaelbauer/4564153 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; | |
import com.google.api.client.http.HttpTransport; | |
import com.google.api.client.http.javanet.NetHttpTransport; | |
import com.google.api.client.json.JsonFactory; | |
import com.google.api.client.json.jackson2.JacksonFactory; | |
import com.google.api.services.drive.DriveScopes; | |
import com.google.code.samples.oauth2.OAuth2Authenticator; | |
import com.sun.mail.imap.IMAPStore; | |
import java.io.File; | |
import java.io.IOException; | |
import java.security.GeneralSecurityException; | |
/** | |
* | |
* Usage explanied here: | |
* http://code.google.com/p/java-gmail-imap/wiki/GmailAndXOAUTH2 | |
* | |
*/ | |
public class GMailExample { | |
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); | |
private static final JsonFactory JSON_FACTORY = new JacksonFactory(); | |
private static final String GMAIL_SCOPE = "https://mail.google.com/"; | |
public static void main(String[] args) throws Exception { | |
String authToken = getAccessToken(SingleUserCredentials.EMAIL); | |
OAuth2Authenticator.initialize(); | |
IMAPStore imapSslStore = OAuth2Authenticator.connectToImap("imap.gmail.com", | |
993, | |
"[email protected]", | |
authToken, | |
true); | |
System.out.println("Successfully authenticated to IMAP.\n"); | |
} | |
public static String getAccessToken() throws GeneralSecurityException, IOException { | |
HttpTransport httpTransport = new NetHttpTransport(); | |
JacksonFactory jsonFactory = new JacksonFactory(); | |
GoogleCredential credential = new GoogleCredential.Builder() | |
.setTransport(httpTransport) | |
.setJsonFactory(jsonFactory) | |
.setServiceAccountId(SingleUserCredentials.SERVICE_ACCOUNT_EMAIL) | |
.setServiceAccountScopes(GMAIL_SCOPE) | |
.setServiceAccountPrivateKeyFromP12File( | |
new java.io.File(SingleUserCredentials.SERVICE_ACCOUNT_PKCS12_FILE_PATH)) | |
.build(); | |
credential.refreshToken(); | |
return credential.getAccessToken(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment