private static Folder getMailInbox(Store store) {

    Folder folder = null;
    Folder inboxfolder = null;

    try {
      folder = store.getDefaultFolder();
      if (folder == null) throw new Exception("No default folder");
      inboxfolder = folder.getFolder("INBOX");
      if (inboxfolder == null) throw new Exception("No INBOX");
      inboxfolder.open(Folder.READ_ONLY);

      Message[] msgs = inboxfolder.getMessages();

      FetchProfile fp = new FetchProfile();
      fp.add("Subject");
      inboxfolder.fetch(msgs, fp);
      return inboxfolder;

    } catch (NoSuchProviderException ex) {
      ex.printStackTrace();
    } catch (MessagingException ex) {
      ex.printStackTrace();
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {

    }

    return null;
  }
  @Override
  public Collection<IridiumMessage> pollMessages(Date timeSince) throws Exception {

    if (askGmailPassword || gmailPassword == null || gmailUsername == null) {
      Pair<String, String> credentials =
          GuiUtils.askCredentials(
              ConfigFetch.getSuperParentFrame(),
              "Enter Gmail Credentials",
              getGmailUsername(),
              getGmailPassword());
      if (credentials == null) return null;
      setGmailUsername(credentials.first());
      setGmailPassword(credentials.second());
      PluginUtils.saveProperties("conf/rockblock.props", this);
      askGmailPassword = false;
    }

    Properties props = new Properties();
    props.put("mail.store.protocol", "imaps");
    ArrayList<IridiumMessage> messages = new ArrayList<>();
    try {
      Session session = Session.getDefaultInstance(props, null);
      Store store = session.getStore("imaps");
      store.connect("imap.gmail.com", getGmailUsername(), getGmailPassword());

      Folder inbox = store.getFolder("Inbox");
      inbox.open(Folder.READ_ONLY);
      int numMsgs = inbox.getMessageCount();

      for (int i = numMsgs; i > 0; i--) {
        Message m = inbox.getMessage(i);
        if (m.getReceivedDate().before(timeSince)) {
          break;
        } else {
          MimeMultipart mime = (MimeMultipart) m.getContent();
          for (int j = 0; j < mime.getCount(); j++) {
            BodyPart p = mime.getBodyPart(j);
            Matcher matcher = pattern.matcher(p.getContentType());
            if (matcher.matches()) {
              InputStream stream = (InputStream) p.getContent();
              byte[] data = IOUtils.toByteArray(stream);
              IridiumMessage msg = process(data, matcher.group(1));
              if (msg != null) messages.add(msg);
            }
          }
        }
      }
    } catch (NoSuchProviderException ex) {
      ex.printStackTrace();
      System.exit(1);
    } catch (MessagingException ex) {
      ex.printStackTrace();
      System.exit(2);
    }

    return messages;
  }
예제 #3
0
  /**
   * Funkcija koja se poziva pritiskom na određeni gumb i preusmjerava na temelju povratne
   * vrijednosti na željenu stranicu. Provjerava da li su uneseni podaci u log in-u ispravni.
   *
   * @return
   */
  public Boolean citajPoruke() {
    Session session = null;
    Store store = null;
    Folder folder = null;

    session = Session.getDefaultInstance(System.getProperties(), null);
    try {

      store = session.getStore("imap");
      store.connect(this.getEmailPosluzitelj(), this.getEmailKorisnik(), this.getEmailLozinka());
      uspjesnostAutentifikacije = true;
      return uspjesnostAutentifikacije;

    } catch (AuthenticationFailedException e) {
      uspjesnostAutentifikacije = false;
      e.printStackTrace();
      return uspjesnostAutentifikacije;
    } catch (FolderClosedException e) {
      uspjesnostAutentifikacije = false;
      e.printStackTrace();
      return uspjesnostAutentifikacije;
    } catch (FolderNotFoundException e) {
      uspjesnostAutentifikacije = false;
      e.printStackTrace();
      return uspjesnostAutentifikacije;
    } catch (NoSuchProviderException e) {
      uspjesnostAutentifikacije = false;
      e.printStackTrace();
      return uspjesnostAutentifikacije;
    } catch (ReadOnlyFolderException e) {
      uspjesnostAutentifikacije = false;
      e.printStackTrace();
      return uspjesnostAutentifikacije;
    } catch (StoreClosedException e) {
      uspjesnostAutentifikacije = false;
      e.printStackTrace();
      return uspjesnostAutentifikacije;
    } catch (Exception e) {
      uspjesnostAutentifikacije = false;
      e.printStackTrace();
      return uspjesnostAutentifikacije;
    }
  }
  private void setProperties() {
    Properties emailProperties = System.getProperties();
    emailProperties.put("mail.smtp.port", "587");
    emailProperties.put("mail.smtp.auth", "true");
    emailProperties.put("mail.smtp.starttls.enable", "true");

    mailSession = Session.getDefaultInstance(emailProperties, null);
    /** Sender's credentials */
    String user = "******";
    String password = "******";

    String host = "smtp.gmail.com";
    try {
      mailTransport = mailSession.getTransport("smtp");
      mailTransport.connect(host, user, password);
    } catch (NoSuchProviderException e) {
      e.printStackTrace();
    } catch (MessagingException e) {
      e.printStackTrace();
    }
  }
 public MimeMessage getMessage(String emailSetId, String mailId) {
   String hql =
       "from EmailUserSetting emailset where emailset.id = '" + Integer.valueOf(emailSetId) + "'";
   EmailUserSetting emailUserSetting = emailUserSettingDao.findEmailUserSetting(hql);
   Properties props = new Properties();
   Session session = Session.getDefaultInstance(props, null);
   Store store = null;
   Message message[] = null;
   try {
     store = session.getStore("pop3");
     store.connect(
         emailUserSetting.getPopService(),
         emailUserSetting.getEmailAddress(),
         emailUserSetting.getPassword());
     Folder folder = store.getFolder("INBOX");
     folder.open(Folder.READ_ONLY);
     message = folder.getMessages();
   } catch (NoSuchProviderException e) {
     e.printStackTrace();
   } catch (MessagingException e) {
     e.printStackTrace();
   }
   // System.out.println("Messages's length: "+message.length);
   MimeMessage pmm = null;
   for (int i = 0; i < message.length; i++) {
     pmm = (MimeMessage) message[i];
     String eId = null;
     try {
       eId = pmm.getMessageID();
     } catch (MessagingException e) {
       e.printStackTrace();
     }
     if (eId != null && eId.equals(mailId)) {
       return pmm;
     }
   }
   return null;
 }
  public static Store getEmailStore(
      String emailServer, String user, String password, String provider) {
    Session session;
    Store store = null;

    Properties props = System.getProperties();
    props.setProperty("mail.pop3s.rsetbeforequit", "false");
    props.setProperty("mail.pop3.rsetbeforequit", "false");
    session = Session.getInstance(props, null);
    try {
      store = session.getStore(provider);
      store.connect(emailServer, user, password);

      return store;
    } catch (NoSuchProviderException ex) {
      ex.printStackTrace();
    } catch (MessagingException ex) {
      ex.printStackTrace();
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    return store;
  }
예제 #7
0
  public static void main(String args[]) {

    String host = "imap.gmail.com";
    String port = "993";
    String userName = args[0];
    String password = args[1];
    String saveDirectory = "/Users/yjg131/Documents";

    /* adding registered users
     * ideally this should be sourced from db
     */
    List<String> registeredUsers = new ArrayList<String>();
    registeredUsers.add("Krishna Nimmagadda <*****@*****.**>");

    // properties for server and SSL setting
    Properties properties = new Properties();
    properties.put("mail.imap.host", host);
    properties.put("mail.imap.port", port);
    properties.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    properties.setProperty("mail.imap.socketFactory.fallback", "false");
    properties.setProperty("mail.imap.socketFactory.port", String.valueOf(port));

    Session session = Session.getDefaultInstance(properties);

    try {
      // connects to the message store
      Store store = session.getStore("imap");
      store.connect(userName, password);

      // opens the inbox folder
      Folder folderInbox = store.getFolder("INBOX");
      folderInbox.open(Folder.READ_ONLY);

      // fetches new messages from server
      Message[] arrayMessages = folderInbox.getMessages();

      List<FirebaseMessage> firebaseMessages = new ArrayList<FirebaseMessage>();

      // process individual message
      for (int i = 0; i < arrayMessages.length; i++) {
        // Message message = arrayMessages[i];
        Address[] fromAddress = arrayMessages[i].getFrom();
        String from = fromAddress[0].toString();
        String subject = arrayMessages[i].getSubject();
        String sentDate = arrayMessages[i].getSentDate().toString();
        String contentType = arrayMessages[i].getContentType();
        String messageContent = "";
        String attachFiles = "";
        String base64EncodedAttach = "";

        if (contentType.contains("multipart") && registeredUsers.contains(from)) {
          System.out.println("Subject: " + subject);
          // content may contain attachments
          Multipart multiPart = (Multipart) arrayMessages[i].getContent();
          int numberOfParts = multiPart.getCount();
          for (int partCount = 0; partCount < numberOfParts; partCount++) {
            MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
            if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
              // this part is attachment
              String fileName = part.getFileName();
              System.out.println("Attachment Name: " + fileName);
              attachFiles += fileName + ",";
              part.saveFile(saveDirectory + File.separator + fileName);
              base64EncodedAttach += base64Encode(saveDirectory + File.separator + fileName) + ",";
              System.out.println(base64EncodedAttach);
            } else {
              // this part may be the message content
              messageContent = part.getContent().toString();
            }
          }
          if (attachFiles.length() > 1) {
            attachFiles = attachFiles.substring(0, attachFiles.length() - 1);
          }
          if (base64EncodedAttach.length() > 1) {
            base64EncodedAttach =
                base64EncodedAttach.substring(0, base64EncodedAttach.length() - 1);
          }

          // construct a firebase message
          FirebaseMessage firebaseMessage = new FirebaseMessage();
          firebaseMessage.setFromAddress(from);
          firebaseMessage.setSubject(subject);
          firebaseMessage.setEncodedAttach(base64EncodedAttach);

          // add message to main list
          firebaseMessages.add(firebaseMessage);
        }
      }

      // push messages to firebase
      pushToFirebase(firebaseMessages);

      // disconnect
      folderInbox.close(false);
      store.close();
    } catch (NoSuchProviderException ex) {
      System.out.println("No provider for pop3.");
      ex.printStackTrace();
    } catch (MessagingException ex) {
      System.out.println("Could not connect to the message store");
      ex.printStackTrace();
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }
예제 #8
0
  public static String readQuikFlixResetLink() {

    properties = new Properties();

    properties.setProperty("mail.host", "imap.gmail.com");

    properties.setProperty("mail.port", "995");

    properties.setProperty("mail.transport.protocol", "imaps");

    session =
        Session.getInstance(
            properties,
            new javax.mail.Authenticator() {

              protected PasswordAuthentication getPasswordAuthentication() {

                return new PasswordAuthentication(userName, password);
              }
            });

    try {

      Thread.sleep(8000L);
      store = session.getStore("imaps");

      store.connect();

      inbox = store.getFolder("INBOX");

      inbox.open(Folder.READ_WRITE);

      Message messages[] = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false));

      System.out.println("Number of mails = " + messages.length);

      for (int i = 0; i < messages.length; i++) {

        Message message = messages[i];

        if (message.getSubject().equalsIgnoreCase("Quickflix Password Reset")) {
          Object content;
          try {
            content = message.getContent();
            if (content instanceof String) {

              message.setFlag(Flags.Flag.DELETED, true);
              resetURL = Jsoup.parse((String) content).select("a").first().text();
              return resetURL;
            }

          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
      }

      inbox.close(true);

      store.close();

    } catch (NoSuchProviderException e) {

      e.printStackTrace();

    } catch (MessagingException e) {

      e.printStackTrace();

    } catch (InterruptedException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }
    return "No Unread Mails from QuickFlix";
  }
예제 #9
0
  /**
   * Sent the message to a plain SMTP server like Waldo
   *
   * @param mmd the MailMessageData to send
   * @return success or failure
   */
  private boolean smtpSend(Mail mail) {
    boolean retVal = true;
    Session session = null;

    try {
      // Create a properties object
      Properties smtpProps = new Properties();

      // Add mail configuration to the properties
      smtpProps.put("mail.transport.protocol", "smtp");

      smtpProps.put("mail.smtp.host", mailConfig.getUrlSmtp());
      smtpProps.put("mail.smtp.port", mailConfig.getPortSmtp());

      if (mailConfig.isSMTPAuth()) {
        Authenticator auth = new SMTPAuthenticator();
        session = Session.getInstance(smtpProps, auth);
      } else session = Session.getDefaultInstance(smtpProps, null);

      // Display the conversation between the client and server
      if (DEBUG) session.setDebug(true);

      // Create a new message
      MimeMessage msg = new MimeMessage(session);

      // Set the single from field
      msg.setFrom(new InternetAddress(mailConfig.getUserEmail()));

      // Set the To, CC, and BCC from their ArrayLists
      for (String emailAddress : mail.getToRecipients())
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress, false));

      if (mail.getCcRecipients() != null)
        for (String emailAddress : mail.getCcRecipients())
          if (!emailAddress.equals(""))
            msg.addRecipient(Message.RecipientType.CC, new InternetAddress(emailAddress, false));

      if (mail.getBccRecipients() != null)
        for (String emailAddress : mail.getBccRecipients())
          if (!emailAddress.equals(""))
            msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(emailAddress, false));

      // Set the subject
      msg.setSubject(mail.getSubject());

      // Set the message body
      msg.setText(mail.getContent());

      // Set some other header information
      msg.setHeader("X-Mailer", "Comp Sci Tech Mailer");
      msg.setSentDate(new Date());

      if (mailConfig.isSMTPAuth()) {
        Transport transport = session.getTransport();

        transport.connect();
        transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
        transport.close();
      } else Transport.send(msg);

    } catch (NoSuchProviderException e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(
          null,
          "There is no server at the SMTP address.",
          "SMTP-NoSuchProviderException",
          JOptionPane.ERROR_MESSAGE);
      logger.log(Level.WARNING, "There is no server at the SMTP address.", e);
      retVal = false;
    } catch (AddressException e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(
          null,
          "There is an error in a recipient's address.",
          "SMTP-AddressException",
          JOptionPane.ERROR_MESSAGE);
      logger.log(Level.WARNING, "There is an error in a recipient's address.", e);
      retVal = false;
    } catch (MessagingException e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(
          null,
          "There is a problem with the message.",
          "SMTP-MessagingException",
          JOptionPane.ERROR_MESSAGE);
      logger.log(Level.WARNING, "There is a problem with the message.", e);
      retVal = false;
    } catch (Exception e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(
          null,
          "There has been an unknown error.",
          "SMTP-UnknownException",
          JOptionPane.ERROR_MESSAGE);
      logger.log(Level.WARNING, "There has been an unknown error.", e);
      retVal = false;
    }
    return retVal;
  }
예제 #10
0
  /**
   * Sent the message to a Gmail account
   *
   * @param mmd the MailMessageData to send
   * @return success or failure
   */
  public boolean gmailSend(Mail mail) {
    boolean retVal = true;
    Transport transport = null;

    try {
      // Create a properties object
      Properties smtpProps = new Properties();

      // Add mail configuration to the properties
      smtpProps.put("mail.transport.protocol", "smtps");
      smtpProps.put("mail.smtps.host", mailConfig.getUrlSmtp());
      smtpProps.put("mail.smtps.auth", "true");
      smtpProps.put("mail.smtps.quitwait", "false");

      // Create a mail session
      Session mailSession = Session.getDefaultInstance(smtpProps);

      // Display the conversation between the client and server
      if (DEBUG) mailSession.setDebug(true);

      // Instantiate the transport object
      transport = mailSession.getTransport();

      // Create a new message
      MimeMessage msg = new MimeMessage(mailSession);

      // Set the To, CC, and BCC from their ArrayLists
      for (String emailAddress : mail.getToRecipients())
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress, false));

      if (mail.getCcRecipients() != null)
        for (String emailAddress : mail.getCcRecipients())
          msg.addRecipient(Message.RecipientType.CC, new InternetAddress(emailAddress, false));

      if (mail.getBccRecipients() != null)
        for (String emailAddress : mail.getBccRecipients())
          msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(emailAddress, false));

      // Set the subject line
      msg.setSubject(mail.getSubject());
      // Set the message body
      msg.setText(mail.getContent());

      // Set some other header information
      msg.setHeader("X-Mailer", "Comp Sci Tech Mailer");
      msg.setSentDate(new Date());

      // Connect and authenticate to the server
      transport.connect(
          mailConfig.getUrlSmtp(),
          mailConfig.getPortSmtp(),
          mailConfig.getUserNamePop3(),
          mailConfig.getUserPassPop3());

      // Send the message
      transport.sendMessage(msg, msg.getAllRecipients());

      // Close the connection
      transport.close();

    } catch (NoSuchProviderException e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(
          null,
          "There is no server at the SMTP address.",
          "Gmail-NoSuchProviderException",
          JOptionPane.ERROR_MESSAGE);
      logger.log(Level.WARNING, "There is no server at the SMTP address.", e);
      retVal = false;
    } catch (AddressException e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(
          null,
          "There is an error in a recipient's address.",
          "Gmail-AddressException",
          JOptionPane.ERROR_MESSAGE);
      logger.log(Level.WARNING, "There is an error in a recipient's address.", e);
      retVal = false;
    } catch (MessagingException e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(
          null,
          "There is a problem with the message.",
          "Gmail-MessagingException",
          JOptionPane.ERROR_MESSAGE);
      logger.log(Level.WARNING, "There is a problem with the message.", e);
      retVal = false;
    } catch (Exception e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(
          null,
          "There has been an unknown error.",
          "Gmail-UnknownException",
          JOptionPane.ERROR_MESSAGE);
      logger.log(Level.WARNING, "There has been an unknown error.", e);
      retVal = false;
    }
    return retVal;
  }
예제 #11
0
  /**
   * 发送邮件
   *
   * @param String subject 邮件标题
   * @param String content 邮件内容
   * @param String[] toAddresses 收件人地址
   * @param String[] ccAddresses 抄送人地址
   * @param String[] fileDirs 文件绝对路径
   * @param String[] fileNames 显示文件名(不含后缀名)
   * @return 发送是否成功
   */
  public boolean sendMessage(
      String subject,
      String content,
      String[] toAddresses,
      String[] ccAddresses,
      String[] fileDirs,
      String[] fileNames) {
    try {
      Properties props = new Properties();
      props.setProperty("mail.transport.protocol", "smtp");
      props.setProperty("mail.auth", "true");
      props.setProperty("mail.debug", mailDebug ? "true" : "false");
      props.setProperty("mail.smtp.host", smtpHost); // Get session					

      Session session = Session.getInstance(props);
      // 创建邮件
      Message message = new MimeMessage(session);
      // 设置来源
      if (from == null || "".equals(from)) {
        message.setFrom(new InternetAddress(userName));
      } else {
        message.setFrom(new InternetAddress(from));
      }
      // 邮件标题
      message.setSubject(subject);

      // 创建邮件空间
      Multipart multipart = new MimeMultipart();

      // 创建邮件内容数据
      MimeBodyPart messageBodyPart = new MimeBodyPart(); // fill message
      // 创建邮件文字内容
      messageBodyPart.setContent(content, "text/html;charset=UTF-8");
      // 将邮件内容添加到邮件中
      multipart.addBodyPart(messageBodyPart); // Part two is attachment

      // 设置附件
      if (fileDirs != null) {
        for (int i = 0; i < fileDirs.length; i++) {
          //					String fileDir = new String(fileDirs[i].getBytes("UTF-8"),"ISO8859-1");
          String fileDir = fileDirs[i];
          // 创见附件
          messageBodyPart = new MimeBodyPart();
          // 设置附件文件地址
          DataSource source = new FileDataSource(fileDir);
          // 载入附件数据
          messageBodyPart.setDataHandler(new DataHandler(source));
          // 设置附件显示名称 包括后缀
          if (fileNames != null
              && fileNames.length > i
              && fileNames[i] != null
              && !"".equals(fileNames[i])) {
            String fileName = new String(fileNames[i].getBytes("UTF-8"), "ISO8859-1");
            messageBodyPart.setFileName(fileName + fileDir.substring(fileDir.lastIndexOf(".")));
          } else {
            if (fileDir.lastIndexOf("/") > 0) {
              messageBodyPart.setFileName(fileDir.substring(fileDir.lastIndexOf("/") + 1));
            } else {
              messageBodyPart.setFileName(fileDir.substring(fileDir.lastIndexOf("\\") + 1));
            }
          }
          // 将附件添加到邮件中
          multipart.addBodyPart(messageBodyPart); // Put parts in message
        }
      }

      // 将邮件内容放入邮件中
      message.setContent(multipart); // Send the message		

      // 整合发件地址 5 5
      Address[] addresses;
      if (ccAddresses == null) {
        addresses = new Address[toAddresses.length];
      } else {
        addresses = new Address[toAddresses.length + ccAddresses.length];
      }

      // 创建收件人地址
      Address[] to_Addresses = new Address[toAddresses.length];
      for (int i = 0; i < toAddresses.length; i++) {
        to_Addresses[i] = new InternetAddress(toAddresses[i]);
        addresses[i] = to_Addresses[i];
      }
      // 创建抄送人地址
      if (ccAddresses != null) {
        Address[] cc_Addresses = new Address[ccAddresses.length];
        for (int i = 0; i < ccAddresses.length; i++) {
          cc_Addresses[i] = new InternetAddress(ccAddresses[i]);
          addresses[toAddresses.length + i] = cc_Addresses[i];
        }
        // 设置抄送人
        message.addRecipients(Message.RecipientType.CC, cc_Addresses);
      }
      Transport transport = session.getTransport();
      // 连接服务器
      transport.connect(smtpHost, smtpPost, userName, passWord);

      // 设置收件人
      message.addRecipients(Message.RecipientType.TO, to_Addresses);

      // 发送邮件
      transport.sendMessage(message, addresses);

      transport.close();
      return true;
    } catch (AddressException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (NoSuchProviderException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (MessagingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return false;
  }
  public GenerateClientInboxView() throws IOException {

    JLabel inboxLabel = new JLabel("Received Emails");
    /*GridBagConstraints inboxConstraints = new GridBagConstraints();
    inboxConstraints.weightx= inboxConstraints.weighty= 1.0;
           inboxConstraints.gridx = 0;
           inboxConstraints.gridy = 0;
           inboxConstraints.gridwidth = 0;
           inboxConstraints.anchor = GridBagConstraints.PAGE_START;
           inbox.add(inboxLabel, inboxConstraints);*/
    String[] subjectToDisplay = new String[1000];

    Files.walk(Paths.get("inbox/"))
        .forEach(
            filePath -> {
              if (Files.isRegularFile(filePath)) {
                this.counter++;
              }
            });
    System.out.println(counter);
    MimeMessage[] messages = new MimeMessage[counter];
    for (int i = 0; i < counter - 1; i++) {
      fileNameForEachEmail[i] = "inbox" + File.separator + "inboxEmail" + i + ".eml";
      try (FileInputStream inboxFile = new FileInputStream(fileNameForEachEmail[i])) {
        try {
          Properties props = new Properties();

          props.setProperty("mail.store.protocol", "imaps");

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

          InputStream source = inboxFile;
          messages[i] = new MimeMessage(session, source);

          subjectToDisplay[i] = messages[i].getSubject().toString();
          System.out.println("From : " + messages[i].getFrom()[0]);
          System.out.println("--------------");
          System.out.println("Body : " + messages[i].getContent());
          /*Properties props = new Properties();

          props.setProperty("mail.store.protocol", "imaps");

          Session session = Session.getDefaultInstance(props, null);
          Store store = session.getStore("imaps");
          store.connect("imap.gmail.com", "*****@*****.**", "eternaldoom12");
          //create the folder object and open it
          Folder emailFolder = store.getFolder("INBOX");
          emailFolder.open(Folder.READ_ONLY);

          // retrieve the messages from the folder in an array and print it
          Message[] messages = emailFolder.getMessages();
          System.out.println("messages.length---" + messages.length);
          for(int i = 0; i<messages.length; i++){
              subjectToDisplay[i] = messages[i].getSubject();
          }*/

        } catch (NoSuchProviderException e) {
          e.printStackTrace();
        } catch (MessagingException e) {
          e.printStackTrace();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }

      JList listOfEmails = new JList(subjectToDisplay);
      listOfEmails.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      MouseListener mouseListener =
          new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
              if (e.getClickCount() == 2) {
                String selectedItem = (String) listOfEmails.getSelectedValue();
                int location = listOfEmails.getSelectedIndex();
                System.out.println(selectedItem);
                try {
                  DisplayContentOfEmail displaycontent =
                      new DisplayContentOfEmail(selectedItem, location);
                } catch (IOException ex) {
                  Logger.getLogger(GenerateClientInboxView.class.getName())
                      .log(Level.SEVERE, null, ex);
                }
              }
            }
          };

      listOfEmails.addMouseListener(mouseListener);
      /*inboxConstraints.gridx = 0;
      inboxConstraints.gridy = 1;*/
      JScrollPane inboxListScrollabel = new JScrollPane(listOfEmails);
      inbox.add(inboxLabel, BorderLayout.PAGE_START);
      inbox.add(inboxListScrollabel, BorderLayout.CENTER);
    }
  }
  public String getMessages(String userId, String emailSetId) {

    String hql =
        "from EmailUserSetting emailset where emailset.id = '" + Integer.valueOf(emailSetId) + "'";
    EmailUserSetting emailUserSetting = emailUserSettingDao.findEmailUserSetting(hql);
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    Store store = null;
    Message message[] = null;
    try {
      store = session.getStore("pop3");
      store.connect(
          emailUserSetting.getPopService(),
          emailUserSetting.getEmailAddress(),
          emailUserSetting.getPassword());
      Folder folder = store.getFolder("INBOX");
      folder.open(Folder.READ_ONLY);
      message = folder.getMessages();
    } catch (NoSuchProviderException e) {
      e.printStackTrace();
    } catch (MessagingException e) {
      e.printStackTrace();
    }
    System.out.println("Messages's length: " + message.length);
    PraseMimeMessage pmm = null;
    String jsonString = "{'mails':[";
    for (int i = 0; i < message.length; i++) {
      pmm = new PraseMimeMessage((MimeMessage) message[i]);
      try {
        String mailString = "{";
        mailString += "'mailId' : '" + pmm.getMessageId() + "',";
        mailString += "'theme':'" + pmm.getSubject() + "',";
        mailString += "'sender':'" + pmm.getFrom() + "',";
        pmm.setDateFormat("yy年MM月dd日  HH:mm:ss");
        mailString += "'time':'" + pmm.getSentDate() + "',";
        mailString += "'files':'";
        if (pmm.isContainAttach((Part) message[i])) {
          List<String> files = pmm.getFilenames();
          for (int j = 0; j < files.size(); j++) {
            mailString += files.get(j) + ";";
          }
          mailString += "',";
        } else {
          mailString += "',";
        }
        pmm.getMailContent((Part) message[i]);
        String content = pmm.getBodyText();
        content = content.replaceAll("\r|\n", "");
        mailString += "'content':'" + content + "'";

        mailString += "},";

        jsonString += mailString;
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    jsonString = jsonString.substring(0, jsonString.length() - 1);
    jsonString += "]}";
    System.out.println(jsonString);
    return jsonString;
  }
예제 #14
0
  public void run() {
    while (!stop) {

      String line;
      ArrayList getMail = new ArrayList();

      BufferedReader reader;
      Properties props = System.getProperties();
      props.setProperty("mail.store.protocol", "imaps");
      try {
        reader = new BufferedReader(new FileReader("D:\\HomeControlPanelMailInfo.txt"));

        while ((line = reader.readLine()) != null) getMail.add(line);

        reader.close();
        String user = (String) getMail.get(1);
        String password = (String) getMail.get(2);
        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");
        store.connect("imap.gmail.com", user, password);
        System.out.println(store);

        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_WRITE);

        FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
        Message[] messages = inbox.search(ft);

        for (int i = 0; i < messages.length; i++) {
          System.out.println("------------ Message " + (i + 1) + " ------------");

          String subject = messages[i].getSubject();

          if (subject.toLowerCase().equals("on")) {
            Communicator.writeData("o");
            GUI.txtLog.append("Email was retrieved successfully!! \n");
          }
          if (subject.toLowerCase().equals("off")) {
            Communicator.writeData("c");
            GUI.txtLog.append("Email was retrieved successfully!! \n");

          } else if (subject != null) {
            System.out.println("subject:" + subject);
          }

          Date sent = messages[i].getSentDate();
          if (sent != null) {
            System.out.println("Sent: " + sent);
          }
          /*
           * Body and date of message if needed
           *
           * System.out.println(); System.out.println("Message : "); if
           * (messages[i].getContentType().toLowerCase()
           * .contains("text/plain")) {
           * System.out.println(messages[i].getContent().toString()); }
           * else { Multipart multipart = (Multipart)
           * messages[i].getContent();
           *
           * for (int x = 0; x < multipart.getCount(); x++) { BodyPart
           * bodyPart = multipart.getBodyPart(x);
           *
           * String disposition = bodyPart.getDisposition();
           *
           * if (disposition != null &&
           * (disposition.equals(BodyPart.ATTACHMENT))) {
           * System.out.println("Mail have some attachment : ");
           *
           * DataHandler handler = bodyPart.getDataHandler();
           * System.out.println("file name : " + handler.getName()); }
           * else { System.out.println(bodyPart.getContent()); } }
           * System.out.println(); }
           */

          messages[i].setFlag(Flags.Flag.DELETED, true);
        }

        inbox.close(true);
        store.close();
        Thread.sleep(5000);
        // Thread thread = new getMail();

        // thread.start();

      } catch (NoSuchProviderException e) {
        e.printStackTrace();
        GUI.system_log.setForeground(Color.red);
        GUI.system_log.append("There was a problem with the provider!! \n");
      } catch (MessagingException e) {
        e.printStackTrace();
        GUI.system_log.setForeground(Color.red);
        GUI.system_log.append("There was a problem with authentication!! \n");
      } catch (IOException e) {
        e.printStackTrace();
        GUI.system_log.setForeground(Color.red);
        GUI.system_log.append("There was a problem with the file info!! \n");
      } catch (InterruptedException e) {
        GUI.system_log.setForeground(Color.red);
        GUI.system_log.append("The process was interrupted!! \n");
        e.printStackTrace();
      }
    }
  }