public String getMessageThread(String threadId) {
    String returnVal = "";
    JSONObject threadDetails = new JSONObject();
    try {

      Gmail service =
          new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
              .setApplicationName("Gmail Quickstart")
              .build();
      com.google.api.services.gmail.model.Thread thread =
          service.users().threads().get("me", threadId).execute();
      System.out.println("Thread id: " + thread.getId());
      System.out.println("No. of messages in this thread: " + thread.getMessages().size());
      List<Message> messages = thread.getMessages();
      if (messages != null) {
        for (Message message : messages) {
          Message msg1 = service.users().messages().get("me", message.getId()).execute();
          // returnVal = returnVal + getMessage(message.getId());
          returnVal = returnVal + getMessageDetails(message.getId()).get("body");
        }

        System.out.println(thread.toPrettyString());
      }
      threadDetails.put("message", returnVal);
      return threadDetails.toJSONString();
    } catch (IOException ex) {
      Logger.getLogger(GoogleAuthHelper.class.getName()).log(Level.SEVERE, null, ex);
      return "error";
    }
  }
  public Map getBareGmailMessageDetails(String messageId) {
    Map<String, Object> messageDetails = new HashMap<String, Object>();
    try {
      Gmail service =
          new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
              .setApplicationName("Gmail Quickstart")
              .build();
      Message message =
          service
              .users()
              .messages()
              .get("me", messageId)
              .setFormat("full")
              .setFields("id,payload,sizeEstimate,snippet,threadId")
              .execute();
      List<MessagePartHeader> headers = message.getPayload().getHeaders();
      for (MessagePartHeader header : headers) {
        if (header.getName().equals("From")
            || header.getName().equals("Date")
            || header.getName().equals("Subject")
            || header.getName().equals("To")
            || header.getName().equals("CC")) {
          messageDetails.put(header.getName().toLowerCase(), header.getValue());
        }
      }
      messageDetails.put("snippet", message.getSnippet());
      messageDetails.put("threadId", message.getThreadId());
      messageDetails.put("id", message.getId());
      // messageDetails.put("body",message.getPayload().getBody().getData());

    } catch (IOException ex) {
      Logger.getLogger(GoogleAuthHelper.class.getName()).log(Level.SEVERE, null, ex);
    }
    return messageDetails;
  }
  public Map getBareMessageDetails(String messageId) {
    Map<String, Object> messageDetails = new HashMap<String, Object>();
    try {
      Gmail service =
          new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
              .setApplicationName("Gmail Quickstart")
              .build();
      Message message = service.users().messages().get("me", messageId).setFormat("raw").execute();

      byte[] emailBytes = Base64.decodeBase64(message.getRaw());

      Properties props = new Properties();
      Session session = Session.getDefaultInstance(props, null);

      MimeMessage email = new MimeMessage(session, new ByteArrayInputStream(emailBytes));
      messageDetails.put("subject", email.getSubject());
      messageDetails.put("from", email.getSender() != null ? email.getSender().toString() : "None");
      messageDetails.put(
          "time", email.getSentDate() != null ? email.getSentDate().toString() : "None");
      messageDetails.put("snippet", message.getSnippet());
      messageDetails.put("threadId", message.getThreadId());
      messageDetails.put("id", message.getId());
      messageDetails.put("body", getText(email));

    } catch (MessagingException ex) {
      Logger.getLogger(GoogleAuthHelper.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
      Logger.getLogger(GoogleAuthHelper.class.getName()).log(Level.SEVERE, null, ex);
    }
    return messageDetails;
  }
  public String getUserEmails(String label) throws IOException {

    Gmail service =
        new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
            .setApplicationName("Gmail Quickstart")
            .build();
    JSONObject ticketDetails = new JSONObject();
    ListMessagesResponse labelMessages =
        service
            .users()
            .messages()
            .list("me") // .setLabelIds(labelIds)
            .setQ("label:inbox label:" + label)
            .setMaxResults(new Long(3))
            .execute();
    List<Message> messages = labelMessages.getMessages();
    JSONArray labelTickets = new JSONArray();
    String returnVal = "";
    if (messages != null) {
      for (Message message : messages) {
        labelTickets.add(new JSONObject(getBareGmailMessageDetails(message.getId())));
      }
      ticketDetails.put("labelTicketDetails", labelTickets);
    }
    return ticketDetails.toJSONString();
  }
 /**
  * Create a Message from an email
  *
  * @param email Email to be set to raw of message
  * @return Message containing base64 encoded email.
  * @throws IOException
  * @throws MessagingException
  */
 private Message createMessageWithEmail(MimeMessage email) throws MessagingException, IOException {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   email.writeTo(baos);
   String encodedEmail = Base64.encodeBase64URLSafeString(baos.toByteArray());
   Message message = new Message();
   message.setRaw(encodedEmail);
   return message;
 }
 public Message execute() {
   Message found = null;
   for (Message message : MockGmail.this.expectedMessageList) {
     if (message.getId() == this.messageId) {
       found = message;
       break;
     }
   }
   return found;
 }
  public String getUserEmails() throws IOException {

    Gmail service =
        new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
            .setApplicationName("Gmail Quickstart")
            .build();
    JSONObject ticketDetails = new JSONObject();
    ListMessagesResponse openMessages =
        service
            .users()
            .messages()
            .list("me") // .setLabelIds(labelIds)
            .setQ("is:unread label:inbox")
            .setMaxResults(new Long(3))
            .execute();
    ticketDetails.put("open", "" + openMessages.getResultSizeEstimate());

    ListMessagesResponse closedMessages =
        service
            .users()
            .messages()
            .list("me") // .setLabelIds(labelIds)
            .setQ("label:inbox label:closed")
            .setMaxResults(new Long(1))
            .execute();
    ticketDetails.put("closed", "" + closedMessages.getResultSizeEstimate());

    ListMessagesResponse pendingMessages =
        service
            .users()
            .messages()
            .list("me") // .setLabelIds(labelIds)
            .setQ("label:inbox label:pending")
            .setMaxResults(new Long(1))
            .execute();
    ticketDetails.put("pending", "" + pendingMessages.getResultSizeEstimate());

    ticketDetails.put("unassigned", "0");
    List<Message> messages = openMessages.getMessages();
    // List<Map> openTickets=new ArrayList<Map>();
    JSONArray openTickets = new JSONArray();
    String returnVal = "";
    // Print ID and snippet of each Thread.
    if (messages != null) {

      for (Message message : messages) {
        openTickets.add(new JSONObject(getBareGmailMessageDetails(message.getId())));
      }
      ticketDetails.put("openTicketDetails", openTickets);
    }
    return ticketDetails.toJSONString();
  }
  /**
   * Send an email from the user's mailbox to its recipient.
   *
   * @param service Authorized Gmail API instance.
   * @param userId User's email address. The special value "me" can be used to indicate the
   *     authenticated user.
   * @param email Email to be sent.
   * @throws MessagingException
   * @throws IOException
   */
  public String sendMessage(String to, String from, String subject, String body)
      throws MessagingException, IOException {

    Gmail service =
        new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
            .setApplicationName("Gmail Quickstart")
            .build();
    MimeMessage email = createMimeMessage(to, from, subject, body);
    Message message = createMessageWithEmail(email);
    message = service.users().messages().send("me", message).execute();

    System.out.println("Message id: " + message.getId());
    System.out.println(message.toPrettyString());
    if (message.getId() != null) {
      return "success";
    } else {
      return "fail";
    }
  }
Example #9
0
  @Override
  public void crawl(Map<String, Object> confidg) {

    try {
      Gmail service = GmailOAuth2Service.getGmailService();
      final String userId = "me";

      ListMessagesResponse response = service.users().messages().list(userId).execute();

      List<Message> messages = new ArrayList<>();

      while (response.getMessages() != null) {
        messages.addAll(response.getMessages());

        if (response.getNextPageToken() != null) {
          String pageToken = response.getNextPageToken();
          response = service.users().messages().list(userId).setPageToken(pageToken).execute();
        } else {
          break;
        }
      }

      for (Message message : messages) {

        try {
          final Message msg = service.users().messages().get(userId, message.getId()).execute();

          System.out.println(msg.toPrettyString());

        } catch (GoogleJsonResponseException ex) {
          System.out.println("Erro na thread id: " + message.getId());
          System.out.println("Erro: " + ex.getMessage());
        }
      }

    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Example #10
0
  @Override
  public File download(Date date) {
    LOGGER.fine("==starting gmail download....");
    try {
      Calendar calendar = Calendar.getInstance();
      calendar.setTime(date);
      calendar.add(Calendar.DATE, -1);
      Date after = calendar.getTime();
      calendar.setTime(date);
      calendar.add(Calendar.DATE, 1);
      Date before = calendar.getTime();
      String query =
          "after:"
              + dateFormat.format(after)
              + " AND before:"
              + dateFormat.format(before)
              + " AND has:attachment AND (filename:.puz OR filename:.jpz)";
      LOGGER.info("Running query: " + query);
      ListMessagesResponse response =
          gmailService.users().messages().list("me").setQ(query).execute();
      LOGGER.fine("==Found " + neverNull(response.getMessages()).size() + " messages.");
      for (Message message : neverNull(response.getMessages())) {
        String singleFilename = "";

        Message fetched = gmailService.users().messages().get("me", message.getId()).execute();
        LOGGER.fine("==Fetched message " + fetched.getId());
        HashMap<String, MessagePart> toDownload = new HashMap<>();
        scanParts(fetched.getPayload().getParts(), toDownload);
        for (Map.Entry<String, MessagePart> entry : toDownload.entrySet()) {
          LOGGER.info("==Reading : " + singleFilename);
          String source = getSender(fetched.getPayload().getHeaders());
          String filename =
              (date.getYear() + 1900)
                  + "-"
                  + (date.getMonth() + 1)
                  + "-"
                  + date.getDate()
                  + "-"
                  + source
                  + "-"
                  + singleFilename.replaceAll(" ", "")
                  + ".puz";
          File destination = new File(CROSSWORDS, filename);
          if (!destination.exists()) {
            byte[] data =
                entry.getValue().getBody().getAttachmentId() != null
                    ? gmailService
                        .users()
                        .messages()
                        .attachments()
                        .get("me", message.getId(), entry.getValue().getBody().getAttachmentId())
                        .execute()
                        .decodeData()
                    : entry.getValue().getBody().decodeData();
            Puzzle puzzle =
                singleFilename.endsWith("jpz")
                    ? JPZIO.readPuzzle(new ByteArrayInputStream(data))
                    : IO.loadNative(new DataInputStream(new ByteArrayInputStream(data)));
            puzzle.setDate(date);
            puzzle.setSource(source);
            puzzle.setSourceUrl("gmail://" + fetched.getId());
            puzzle.setUpdatable(false);
            date = getSentDate(fetched.getPayload().getHeaders());
            LOGGER.info("Downloaded " + filename);
            IO.save(puzzle, destination);
          }
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }