/**
   * Process the MimeMessage from signed Mail to get attachments and save them to disk.
   *
   * @param mime
   * @return
   * @throws MessagingException
   * @throws IOException
   */
  private String processAttachmentsOfSignedMail(MimeMessage mime)
      throws IOException, MessagingException {
    List<Attachment> attachList = new ArrayList<Attachment>();

    // Get the content of the messsage, it's an Multipart object like a package including all the
    // email text and attachment.
    Multipart multi1 = (Multipart) mime.getContent();

    // process each part in order.
    for (int i = 0, n = multi1.getCount(); i < n; i++) {
      // unpack, get each part of Multipart, part 0 may email text and part 1 may attachment. Or it
      // is another embedded Multipart.
      Part part2 = multi1.getBodyPart(i);
      // determine Part is email text or Multipart.
      if (part2.getContent() instanceof Multipart) {
        Multipart multi2 = (Multipart) part2.getContent();
        // First, verify the quantity and size of attachments.
        boolean isValidMailMsg = this.isValidMailMsg(multi2);
        if (isValidMailMsg) {
          // process the content in multi2.
          for (int j = 0; j < multi2.getCount(); j++) {
            Part part3 = multi2.getBodyPart(j);
            if (part3.isMimeType("multipart/related")) {
              if (part3.getContent() instanceof Multipart) {
                Multipart multi3 = (Multipart) part3.getContent();
                for (int m = 0; m < multi3.getCount(); m++) {
                  Part part4 = multi3.getBodyPart(m);
                  if (!part4.isMimeType("multipart/alternative")) {
                    // This is an embedded picture, save it.
                    this.saveAttachment(part4, attachList);
                  }
                }
              }
            } else {
              // Save the attachment.
              String disposition = part3.getDisposition();
              if (disposition != null && Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
                this.saveAttachment(part3, attachList);
              }
            }
          }
        }
      } else {
        // Process the attachment.(This is a certificate file.)
        String disposition = part2.getDisposition();
        if (disposition != null && Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
          this.saveAttachment(part2, attachList);
        }
      }
    }
    return JSONArray.fromObject(attachList).toString();
  }
Esempio n. 2
0
 public static String getBodyPartContentType(MimeMultipart mimeMultipart)
     throws MessagingException {
   for (int i = 0; i < mimeMultipart.getCount(); i++) {
     BodyPart bodyPart = mimeMultipart.getBodyPart(i);
     // ignore attachment
     if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
       return bodyPart.getContentType();
     }
   }
   return StringUtils.EMPTY;
 }
  /**
   * Process the MimeMessage from simple Mail to get attachments and save them to disk.
   *
   * @param mime
   * @return
   * @throws IOException
   * @throws MessagingException
   */
  private String processAttachmentsOfSimpleMail(MimeMessage mime)
      throws IOException, MessagingException {
    List<Attachment> attachList = new ArrayList<Attachment>();

    if (mime.getContent() instanceof Multipart) {
      // Get the content of the messsage, it's an Multipart object like a package including all the
      // email text and attachment.
      Multipart multi = (Multipart) mime.getContent();
      // First, verify the quantity and size of attachments.
      boolean isValidMailMsg = this.isValidMailMsg(multi);
      if (isValidMailMsg) {
        // process each part in order.
        for (int i = 0, n = multi.getCount(); i < n; i++) {
          // unpack, get each part of Multipart, part 0 may email text and part 1 may attachment. Or
          // it is another embedded Multipart.
          Part part1 = multi.getBodyPart(i);
          if (part1.isMimeType("multipart/related")) {
            if (part1.getContent() instanceof Multipart) {
              Multipart multi1 = (Multipart) part1.getContent();
              for (int m = 0; m < multi1.getCount(); m++) {
                Part part2 = multi1.getBodyPart(m);
                if (!(part2.isMimeType("multipart/alternative")
                    || part2.isMimeType("text/plain")
                    || part2.isMimeType("text/html"))) {
                  // This is an embedded picture, set it as an attachment.
                  this.saveAttachment(part2, attachList);
                }
              }
            }
          } else {
            String disposition = part1.getDisposition();
            if (disposition != null && Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
              // Save the attachment if it is.
              this.saveAttachment(part1, attachList);
            }
          }
        }
      }
    }
    return JSONArray.fromObject(attachList).toString();
  }
Esempio n. 4
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();
    }
  }
  /**
   * Process the MimeMessage for signed mail with/without attachment.
   *
   * @param mime
   * @param mailMsg
   * @return
   * @throws MessagingException
   * @throws IOException
   * @throws ParseException
   */
  private String processSignedMail(MimeMessage mime, MailMessage mailMsg)
      throws IOException, MessagingException, ParseException {
    this.setMailBasicInfoForMailMsg(mime, mailMsg);

    String txtBody = null;
    String htmlBody = null;
    // Get the content of the messsage, it's an Multipart object like a package including all the
    // email text and attachment.
    Multipart multi1 = (Multipart) mime.getContent();
    // process each part in order.
    for (int i = 0, n = multi1.getCount(); i < n; i++) {
      // unpack, get each part of Multipart, part 0 may email text and part 1 may attachment. Or it
      // is another embedded Multipart.
      Part part2 = multi1.getBodyPart(i);
      // determine Part is email text or Multipart.
      if (part2.getContent() instanceof Multipart) {
        Multipart multi2 = (Multipart) part2.getContent();
        // First, verify the quantity and size of attachments.
        boolean isValidMailMsg = this.isValidMailMsg(multi2);
        if (isValidMailMsg) {
          // process the content in multi2.
          for (int j = 0; j < multi2.getCount(); j++) {
            Part part3 = multi2.getBodyPart(j);
            if (part3.isMimeType("text/plain")
                && !Part.ATTACHMENT.equalsIgnoreCase(part3.getDisposition())) {
              txtBody = part3.getContent().toString();
            } else if (part3.isMimeType("text/html")
                && !Part.ATTACHMENT.equalsIgnoreCase(part3.getDisposition())) {
              htmlBody = part3.getContent().toString();
            } else if (part3.isMimeType("multipart/alternative")) {
              // generally if the content type multipart/alternative, it is email text.
              if (part3.getContent() instanceof Multipart) {
                Multipart multi3 = (Multipart) part3.getContent();
                for (int k = 0; k < multi3.getCount(); k++) {
                  Part part4 = multi3.getBodyPart(k);
                  if (part4.isMimeType("text/plain")
                      && !Part.ATTACHMENT.equalsIgnoreCase(part4.getDisposition())) {
                    txtBody = part4.getContent().toString();
                  } else if (part4.isMimeType("text/html")
                      && !Part.ATTACHMENT.equalsIgnoreCase(part4.getDisposition())) {
                    htmlBody = part4.getContent().toString();
                  }
                }
              }
            } else if (part3.isMimeType("multipart/related")) {
              if (part3.getContent() instanceof Multipart) {
                Multipart multi3 = (Multipart) part3.getContent();
                for (int m = 0; m < multi3.getCount(); m++) {
                  Part part4 = multi3.getBodyPart(m);
                  if (part4.isMimeType("multipart/alternative")) {
                    if (part4.getContent() instanceof Multipart) {
                      Multipart multi4 = (Multipart) part4.getContent();
                      for (int p = 0; p < multi4.getCount(); p++) {
                        Part part5 = multi4.getBodyPart(p);
                        if (part5.isMimeType("text/plain")
                            && !Part.ATTACHMENT.equalsIgnoreCase(part5.getDisposition())) {
                          txtBody = part5.getContent().toString();
                        } else if (part5.isMimeType("text/html")
                            && !Part.ATTACHMENT.equalsIgnoreCase(part5.getDisposition())) {
                          htmlBody = part5.getContent().toString();
                        }
                      }
                    }
                  } else {
                    // This is an embedded picture, set it as an attachment.
                    mailMsg.setHasAttachments(true);
                  }
                }
              }
            } else {
              String disposition = part3.getDisposition();
              if (disposition != null && Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
                mailMsg.setHasAttachments(true);
              }
            }
          }
        }
      } else {
        // This is a certificate file, set it as an attachment
        String disposition = part2.getDisposition();
        if (disposition != null && Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
          mailMsg.setHasAttachments(true);
        }
      }
    }
    if (!isNull(txtBody)) {
      mailMsg.setBody(txtBody);
    } else {
      mailMsg.setBody(htmlBody);
    }
    return JSONObject.fromObject(mailMsg).toString();
  }