Пример #1
0
  public String setMessageLabel(String messageId, String labelName) {
    try {
      Gmail service =
          new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
              .setApplicationName("Gmail Quickstart")
              .build();
      // For now assuming that when a label is set, we make it read also.

      List<String> labelsToRemove = new ArrayList();
      labelsToRemove.add("UNREAD");
      List<String> labelsToAdd = new ArrayList();
      if (labelName != null) {
        // this can be optimized by get all label names once they login
        ListLabelsResponse response = service.users().labels().list("me").execute();
        List<Label> labels = response.getLabels();
        boolean labelExists = false;
        for (Label label : labels) {
          // System.out.println(label.toPrettyString());
          if (label.getName().equalsIgnoreCase(labelName)) {
            labelsToAdd.add(label.getId());
            System.out.println("Adding label:" + labelName);
            labelExists = true;
            break;
          }
        }

        if (!labelExists) {
          Label label =
              new Label()
                  .setName(labelName)
                  .setLabelListVisibility("labelShow")
                  .setMessageListVisibility("show");
          label = service.users().labels().create("me", label).execute();
          labelsToAdd.add(label.getId());
        }
      }

      ModifyMessageRequest mods;
      mods =
          new ModifyMessageRequest().setRemoveLabelIds(labelsToRemove).setAddLabelIds(labelsToAdd);
      Message message = service.users().messages().modify("me", messageId, mods).execute();
      return "success";
    } catch (IOException ioe) {
      System.out.println("ioerror");
      // ioe.printStackTrace();
      return "error";
    }
  }
Пример #2
0
  public static void main(String[] args) throws IOException {
    // Build a new authorized API client service.
    Gmail service = getGmailService();

    // Print the labels in the user's account.
    String user = "******";
    ListLabelsResponse listResponse = service.users().labels().list(user).execute();
    List<Label> labels = listResponse.getLabels();
    if (labels.size() == 0) {
      System.out.println("No labels found.");
    } else {
      System.out.println("Labels:");
      for (Label label : labels) {
        System.out.printf("- %s\n", label.getName());
      }
    }
  }