com.google.api.services.gmail.Gmail Java Examples

The following examples show how to use com.google.api.services.gmail.Gmail. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SendMailWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 6 votes vote down vote up
public Message sendMessage(Gmail service,
                           String to,
                           String from,
                           String subject,
                           String bodyText,
                           Document attachment)
        throws MessagingException, IOException {
    MimeMessage mimeMessage = createEmailWithAttachment(to,
                                                        from,
                                                        subject,
                                                        bodyText,
                                                        attachment);
    Message message = service.users().messages().send(from,
                                                      createMessageWithEmail(mimeMessage)).execute();

    return message;
}
 
Example #2
Source File: GmailVerifierExtension.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
protected Result verifyConnectivity(Map<String, Object> parameters) {
    ResultBuilder builder = ResultBuilder.withStatusAndScope(Result.Status.OK, Scope.CONNECTIVITY);

    try {
        String profile = ConnectorOptions.extractOption(parameters, "userId");
        if (ObjectHelper.isEmpty(profile)) {
            throw new IllegalStateException("The profile parameter has not been not defined");
        }
        GoogleMailConfiguration configuration = setProperties(new GoogleMailConfiguration(), parameters);
        GoogleMailClientFactory clientFactory = new BatchGoogleMailClientFactory();
        Gmail client = clientFactory.makeClient(configuration.getClientId(), configuration.getClientSecret(),
                                                configuration.getApplicationName(), configuration.getRefreshToken(),
                                                configuration.getAccessToken());
        client.users().getProfile(profile).execute();
    } catch (Exception e) {
        ResultErrorBuilder errorBuilder = ResultErrorBuilder.withCodeAndDescription(VerificationError.StandardCode.AUTHENTICATION, e.getMessage())
            .detail("gmail_exception_message", e.getMessage()).detail(VerificationError.ExceptionAttribute.EXCEPTION_CLASS, e.getClass().getName())
            .detail(VerificationError.ExceptionAttribute.EXCEPTION_INSTANCE, e);

        builder.error(errorBuilder.build());
    }

    return builder.build();
}
 
Example #3
Source File: GoogleMailImporter.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
GoogleMailImporter(
    GoogleCredentialFactory credentialFactory, Gmail gmail, Monitor monitor) {
  this.credentialFactory = credentialFactory;
  this.gmail = gmail;
  this.monitor = monitor;
}
 
Example #4
Source File: GoogleMailImporter.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
private synchronized Gmail makeGmailService(TokensAndUrlAuthData authData) {
  Credential credential = credentialFactory.createCredential(authData);
  return new Gmail.Builder(
          credentialFactory.getHttpTransport(), credentialFactory.getJsonFactory(), credential)
      .setApplicationName(GoogleStaticObjects.APP_NAME)
      .build();
}
 
Example #5
Source File: GmailServiceMaker.java    From teammates with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Builds and returns an authorized Gmail client service.
 */
Gmail makeGmailService() throws IOException {
    Credential credential = authorizeAndCreateCredentials();
    return new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
            .setApplicationName("teammates")
            .build();
}
 
Example #6
Source File: GoogleMailExporter.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
private synchronized Gmail makeGmailService(TokensAndUrlAuthData authData) {
  Credential credential = credentialFactory.createCredential(authData);
  return new Gmail.Builder(
      credentialFactory.getHttpTransport(), credentialFactory.getJsonFactory(), credential)
      .setApplicationName(GoogleStaticObjects.APP_NAME)
      .build();
}
 
Example #7
Source File: GmailService.java    From mail-importer with Apache License 2.0 5 votes vote down vote up
Gmail getServiceWithRetries() {
  HttpRequestInitializer httpRequestInitializer =
      request -> {
        credential.initialize(request);
        new UnsuccessfulResponseHandlerChainer().chain(
            request.getUnsuccessfulResponseHandler(),
            new HttpBackOffUnsuccessfulResponseHandler(
                backOffProvider.get()));
      };

  return new Gmail.Builder(httpTransport, jsonFactory, httpRequestInitializer)
      .setApplicationName(GmailServiceModule.APP_NAME)
      .build();
}
 
Example #8
Source File: GmailAuthorizationActivity.java    From PrivacyStreams with Apache License 2.0 5 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(requestCode) {
        case REQUEST_AUTHORIZATION:
            if (resultCode == RESULT_OK) {
                gmailResultListener.onSuccess(mService);
            }
            break;

        case REQUEST_ACCOUNT_PICKER:
            if (resultCode == RESULT_OK && data != null &&
                    data.getExtras() != null) {
                String accountName =
                        data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
                if (accountName != null) {
                    SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
                    editor.putString(PREF_ACCOUNT_NAME,accountName);
                    editor.apply();

                    mCredential.setSelectedAccountName(accountName);

                    mService = new Gmail.Builder(
                                AndroidHttp.newCompatibleTransport(), JacksonFactory.getDefaultInstance(), mCredential)
                                .setApplicationName(AppUtils.getApplicationName(this))
                                .build();
                    gmailResultListener.onSuccess(mService);
                }

            }
            break;
    }
    finish();
}
 
Example #9
Source File: BaseGmailProvider.java    From PrivacyStreams with Apache License 2.0 5 votes vote down vote up
private void checkGmailApiRequirements() {


        String accountName = PreferenceManager.getDefaultSharedPreferences(getContext())
                .getString(PREF_ACCOUNT_NAME, null);

        if (accountName != null) {
            GoogleAccountCredential mCredential = GoogleAccountCredential.usingOAuth2(
                    getContext().getApplicationContext(), Arrays.asList(SCOPES))
                    .setBackOff(new ExponentialBackOff());
            mCredential.setSelectedAccountName(accountName);

            if (!DeviceUtils.isGooglePlayServicesAvailable(getContext())) {
                DeviceUtils.acquireGooglePlayServices(getContext());
            }
            else{
                mService = new Gmail.Builder(
                        AndroidHttp.newCompatibleTransport(), JacksonFactory.getDefaultInstance(), mCredential)
                        .setApplicationName(AppUtils.getApplicationName(getContext()))
                        .build();
                authorized = true;
            }


        } else {
            GmailAuthorizationActivity.setListener(this);
            getContext().startActivity(new Intent(getContext(), GmailAuthorizationActivity.class));
        }

    }
 
Example #10
Source File: ShortyzApplication.java    From shortyz with GNU General Public License v3.0 5 votes vote down vote up
public void updateCredential(SharedPreferences prefs){
	credential = GoogleAccountCredential.usingOAuth2(
			getApplicationContext(), Arrays.asList(GMConstants.SCOPES))
			.setBackOff(new ExponentialBackOff())
			.setSelectedAccountName(prefs.getString(GMConstants.PREF_ACCOUNT_NAME, null));
	if(credential != null && credential.getSelectedAccount() != null) {
		gmailService = new com.google.api.services.gmail.Gmail.Builder(
				transport, jsonFactory, credential)
				.setApplicationName("Shortyz")
				.build();
	} else {
		gmailService = null;
	}
}
 
Example #11
Source File: SendMailWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager workItemManager) {
    String paramTo = (String) workItem.getParameter("To");
    String paramFrom = (String) workItem.getParameter("From");
    String paramSubject = (String) workItem.getParameter("Subject");
    String paramBodyText = (String) workItem.getParameter("BodyText");
    Document paramAttachment = (Document) workItem.getParameter("Attachment");

    try {

        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        Gmail gmailService = auth.getGmailService(appName,
                                                  clientSecret);
        Message outEmailMessage = sendMessage(gmailService,
                                              paramTo,
                                              paramFrom,
                                              paramSubject,
                                              paramBodyText,
                                              paramAttachment);

        workItemManager.completeWorkItem(workItem.getId(),
                                         outEmailMessage);
    } catch (Exception e) {
        handleException(e);
    }
}
 
Example #12
Source File: GoogleMailAuth.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
public Gmail getGmailService(String appName,
                             String clientSecretJSON) {
    try {
        HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        Credential credential = authorize(clientSecretJSON);
        return new Gmail.Builder(HTTP_TRANSPORT,
                                 JSON_FACTORY,
                                 credential)
                .setApplicationName(appName)
                .build();
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example #13
Source File: GoogleMailImporter.java    From data-transfer-project with Apache License 2.0 4 votes vote down vote up
private Gmail getOrCreateGmail(TokensAndUrlAuthData authData) {
  return gmail == null ? makeGmailService(authData) : gmail;
}
 
Example #14
Source File: Authorizer.java    From mail-importer with Apache License 2.0 4 votes vote down vote up
public Credential get() {
  try {
    GoogleClientSecrets clientSecrets = loadGoogleClientSecrets(jsonFactory);

    DataStore<StoredCredential> dataStore = getStoredCredentialDataStore();

    // Allow user to authorize via url.
    GoogleAuthorizationCodeFlow flow =
        new GoogleAuthorizationCodeFlow.Builder(
            httpTransport,
            jsonFactory,
            clientSecrets,
            ImmutableList.of(
                GmailScopes.GMAIL_MODIFY,
                GmailScopes.GMAIL_READONLY))
            .setCredentialDataStore(dataStore)
            .setAccessType("offline")
            .setApprovalPrompt("auto")
            .build();

    // First, see if we have a stored credential for the user.
    Credential credential = flow.loadCredential(user.getEmailAddress());

    // If we don't, prompt them to get one.
    if (credential == null) {
      String url = flow.newAuthorizationUrl()
          .setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI)
          .build();
      System.out.println("Please open the following URL in your browser then "
          + "type the authorization code:\n" + url);

      // Read code entered by user.
      System.out.print("Code: ");
      System.out.flush();
      BufferedReader br = new BufferedReader(
          new InputStreamReader(System.in));
      String code = br.readLine();

      // Generate Credential using retrieved code.
      GoogleTokenResponse response = flow.newTokenRequest(code)
          .setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI)
          .execute();

      credential =
          flow.createAndStoreCredential(response, user.getEmailAddress());
    }

    Gmail gmail = new Gmail.Builder(httpTransport, jsonFactory, credential)
        .setApplicationName(GmailServiceModule.APP_NAME)
        .build();

    Profile profile = gmail.users()
        .getProfile(user.getEmailAddress())
        .execute();

    System.out.println(profile.toPrettyString());
    return credential;
  } catch (IOException exception) {
    throw new RuntimeException(exception);
  }
}
 
Example #15
Source File: GmailDownloader.java    From shortyz with GNU General Public License v3.0 4 votes vote down vote up
public GmailDownloader(Gmail gmailService) {
    this.gmailService = gmailService;
}
 
Example #16
Source File: ShortyzApplication.java    From shortyz with GNU General Public License v3.0 4 votes vote down vote up
public Gmail getGmailService(){
	return gmailService;
}
 
Example #17
Source File: BaseGmailProvider.java    From PrivacyStreams with Apache License 2.0 4 votes vote down vote up
/**
 * When the app just got the authorization and permission from the activity, it goes to this callback.
 */
@Override
public void onSuccess(Gmail service) {
    mService = service;
}
 
Example #18
Source File: GmailHistoryProvider.java    From PrivacyStreams with Apache License 2.0 4 votes vote down vote up
/**
 * When the app just got the authorization and permission from the activity, it goes to this callback.
 */
@Override
public void onSuccess(Gmail service) {
    super.onSuccess(service);
    new FetchEmailTask().execute(buildTimeQuery(mBegin, mEnd));
}
 
Example #19
Source File: GoogleMailExporter.java    From data-transfer-project with Apache License 2.0 4 votes vote down vote up
private Gmail getOrCreateGmail(TokensAndUrlAuthData authData) {
  return gmail == null ? makeGmailService(authData) : gmail;
}
 
Example #20
Source File: GoogleMailExporter.java    From data-transfer-project with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
GoogleMailExporter(GoogleCredentialFactory credentialFactory, Gmail gmail) {
  this.credentialFactory = credentialFactory;
  this.gmail = gmail;
}
 
Example #21
Source File: GmailResultListener.java    From PrivacyStreams with Apache License 2.0 votes vote down vote up
void onSuccess(Gmail service);