コード例 #1
0
ファイル: MailUtils.java プロジェクト: alathon/mailman
  public static String getBody(Message message) throws Exception {
    try {
      message.getContent(); // This might throw an exception...
    } catch (Throwable ex) {
      try {
        // Content could not be resolved for some reason - just get the raw stuff
        return ConvertUtil.inputStreamToString(message.getInputStream());
      } catch (Throwable ex2) {
        // bodystructure is corrupt - get the really raw stuff
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        message.writeTo(out);
        return out.toString();
      }
    }

    // check if message is a normal message or a Multipart message
    if (message.getContent() instanceof MimeMultipart) {
      MultipartResult res = new MailUtils.MultipartResult();
      MailUtils.readMultiPart(res, (MimeMultipart) message.getContent());
      return res.body.isEmpty() ? res.bodyHtml : res.body;
    } else {
      if (message.getContent().toString() != null) {
        return message.getContent().toString();
      }
    }
    return null;
  }
コード例 #2
0
 public void handleMessage(Message message, String contentType)
     throws IOException, MessagingException {
   Log.debug(this, "handleMessage");
   Object objContent = message.getContent();
   if (objContent instanceof Multipart) {
     Log.debug(this, "handleMessage-multipart");
     Multipart multipart = (Multipart) message.getContent();
     this.handleContent(multipart, contentType);
   } else {
     Log.debug(this, "handleMessage-string");
     this.handleStringContent((String) objContent);
   }
 }
コード例 #3
0
ファイル: NewProviderSupport.java プロジェクト: phcd/TAB
 protected int getMessageSize(Message message, Account account)
     throws IOException, MessagingException {
   int count = 0;
   if (account.getLoginName().contains("aol.com") && message.getContent() instanceof Multipart) {
     Multipart multipart = (Multipart) message.getContent();
     for (int i = 0; i < multipart.getCount(); i++) {
       count += multipart.getBodyPart(i).getSize();
     }
   } else {
     count = message.getSize();
   }
   return count;
 }
コード例 #4
0
  public static void main(String[] args) throws MessagingException, IOException {
    IMAPFolder folder = null;
    Store store = null;
    String subject = null;
    Flag flag = null;
    try {
      Properties props = System.getProperties();
      props.setProperty("mail.store.protocol", "imaps");
      props.setProperty("mail.imap.host", "imap.googlemail.com");
      SimpleAuthenticator authenticator =
          new SimpleAuthenticator("*****@*****.**", "hhy8611hhyy");
      Session session = Session.getDefaultInstance(props, null);
      // Session session = Session.getDefaultInstance(props, authenticator);

      store = session.getStore("imaps");
      //          store.connect("imap.googlemail.com","*****@*****.**", "hhy8611hhyy");
      // store.connect("imap.googlemail.com","*****@*****.**", "hhy8611hhyy");

      store.connect("*****@*****.**", "hhy8611hhy");
      // folder = (IMAPFolder) store.getFolder("[Gmail]/Spam"); // This doesn't work for other email
      // account
      folder = (IMAPFolder) store.getFolder("inbox"); // This works for both email account

      if (!folder.isOpen()) folder.open(Folder.READ_WRITE);
      Message[] messages = messages = folder.getMessages(150, 150); // folder.getMessages();
      System.out.println("No of get Messages : " + messages.length);
      System.out.println("No of Messages : " + folder.getMessageCount());
      System.out.println("No of Unread Messages : " + folder.getUnreadMessageCount());
      System.out.println("No of New Messages : " + folder.getNewMessageCount());
      System.out.println(messages.length);
      for (int i = 0; i < messages.length; i++) {

        System.out.println(
            "*****************************************************************************");
        System.out.println("MESSAGE " + (i + 1) + ":");
        Message msg = messages[i];
        // System.out.println(msg.getMessageNumber());
        // Object String;
        // System.out.println(folder.getUID(msg)

        subject = msg.getSubject();

        System.out.println("Subject: " + subject);
        System.out.println("From: " + msg.getFrom()[0]);
        System.out.println("To: " + msg.getAllRecipients()[0]);
        System.out.println("Date: " + msg.getReceivedDate());
        System.out.println("Size: " + msg.getSize());
        System.out.println(msg.getFlags());
        System.out.println("Body: \n" + msg.getContent());
        System.out.println(msg.getContentType());
      }
    } finally {
      if (folder != null && folder.isOpen()) {
        folder.close(true);
      }
      if (store != null) {
        store.close();
      }
    }
  }
コード例 #5
0
  /**
   * metoda preuzmiPoruke preuzima poruke iz odabrane mape i puni listu poruka
   *
   * @throws MessagingException
   * @throws IOException
   */
  private void preuzmiPoruke() throws MessagingException, IOException {
    Message[] messages;

    // Open the INBOX folder
    folder = store.getFolder(this.odabranaMapa);
    folder.open(Folder.READ_ONLY);

    messages = folder.getMessages();

    this.poruke = new ArrayList<Poruka>();

    for (int i = 0; i < messages.length; ++i) {
      Message m = messages[i];
      Poruka p =
          new Poruka(
              m.getHeader("Message-ID")[0],
              m.getSentDate(),
              m.getFrom()[0].toString(),
              m.getSubject(),
              m.getContentType(),
              m.getSize(),
              0,
              m.getFlags(),
              null,
              true,
              true,
              m.getContent().toString());
      // TODO potraziti broj privitaka, sad je hardkodirano da ih je 0

      this.poruke.add(p);
    }
  }
コード例 #6
0
 private String getTokenFromMessage(Message msg) throws IOException, MessagingException {
   String body = ((MimeMultipart) msg.getContent()).getBodyPart(0).getContent().toString();
   // TODO better token extraction
   // this is going to get the wrong string if the first part is not
   // text/plain and the url isn't the last character in the email
   return StringUtils.substringAfterLast(body, "token=");
 }
コード例 #7
0
  /**
   * Test that FolderClosedException is thrown when the timeout occurs when reading the message
   * body.
   */
  @Test
  public void testFolderClosedExceptionBody() {
    TestServer server = null;
    try {
      final POP3Handler handler = new POP3HandlerTimeoutBody();
      server = new TestServer(handler);
      server.start();
      Thread.sleep(1000);

      final Properties properties = new Properties();
      properties.setProperty("mail.pop3.host", "localhost");
      properties.setProperty("mail.pop3.port", "" + server.getPort());
      final Session session = Session.getInstance(properties);
      // session.setDebug(true);

      final Store store = session.getStore("pop3");
      try {
        store.connect("test", "test");
        final Folder folder = store.getFolder("INBOX");
        folder.open(Folder.READ_ONLY);
        Message msg = folder.getMessage(1);
        try {
          msg.getContent();
        } catch (IOException ioex) {
          // expected
          // first attempt detects error return from server
        }
        // second attempt detects closed connection from server
        msg.getContent();

        // Check
        assertFalse(folder.isOpen());
      } catch (FolderClosedException ex) {
        // success!
      } finally {
        store.close();
      }
    } catch (final Exception e) {
      e.printStackTrace();
      fail(e.getMessage());
    } finally {
      if (server != null) {
        server.quit();
      }
    }
  }
コード例 #8
0
ファイル: MailImport.java プロジェクト: gineer01/jgnucashlib
 /** {@inheritDoc}. */
 public InputStream getInputStream() throws IOException {
   try {
     return (InputStream) myMessage.getContent();
   } catch (MessagingException e) {
     LOG.log(Level.SEVERE, "Exception while getting content", e);
     return null;
   }
 }
コード例 #9
0
ファイル: Mail.java プロジェクト: huayuxian/skysail
 public Mail(Message message) {
   try {
     this.subject = message.getSubject();
     this.content = message.getContent();
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
コード例 #10
0
    private String getRawText(Object o) throws MessagingException, IOException {

      String s = null;

      if (o instanceof Multipart) {
        Multipart multi = (Multipart) o;
        for (int i = 0; i < multi.getCount(); i++) {
          s = getRawText(multi.getBodyPart(i));
          if (s != null) {
            if (s.length() > 0) {
              break;
            }
          }
        }
      } else if (o instanceof BodyPart) {
        BodyPart aBodyContent = (BodyPart) o;
        StringTokenizer aTypeTokenizer = new StringTokenizer(aBodyContent.getContentType(), "/");
        String abstractType = aTypeTokenizer.nextToken();
        if (abstractType.compareToIgnoreCase("MESSAGE") == 0) {
          Message inlineMessage = (Message) aBodyContent.getContent();
          s = getRawText(inlineMessage.getContent());
        }
        if (abstractType.compareToIgnoreCase("APPLICATION") == 0) {
          s = "Attached File: " + aBodyContent.getFileName();
        }
        if (abstractType.compareToIgnoreCase("TEXT") == 0) {
          try {
            Object oS = aBodyContent.getContent();
            if (oS instanceof String) {
              s = (String) oS;
            } else {
              throw (new MessagingException("Unkown MIME Type (?): " + oS.getClass()));
            }
          } catch (Exception e) {
            throw (new MessagingException(
                "Unable to read message contents (" + e.getMessage() + ")"));
          }
        }
        if (abstractType.compareToIgnoreCase("MULTIPART") == 0) {
          s = getRawText(aBodyContent.getContent());
        }
      }

      if (o instanceof String) {
        s = (String) o;
      }

      //          else {
      //              if (m.isMimeType("text/html")) {
      //                  s = m.getContent().toString();
      //              }
      //              if (m.isMimeType("text/plain")) {
      //                  s = m.getContent().toString();
      //              }
      //          }

      return s;
    }
コード例 #11
0
  @Test
  public void testCreateOrganizationAndAdminWithConfirmationAndActivation() throws Exception {
    setup.set(PROPERTIES_SYSADMIN_APPROVES_ADMIN_USERS, "true");
    setup.set(PROPERTIES_NOTIFY_ADMIN_OF_ACTIVATION, "true");
    setup.set(PROPERTIES_SYSADMIN_APPROVES_ORGANIZATIONS, "false");
    setup.set(PROPERTIES_ADMIN_USERS_REQUIRE_CONFIRMATION, "true");

    final String orgName = uniqueOrg();
    final String userName = uniqueUsername();
    final String email = uniqueEmail();

    OrganizationOwnerInfo org_owner =
        createOwnerAndOrganization(
            orgName, userName, "Test User", email, "testpassword", false, false);

    assertNotNull(org_owner);

    List<Message> user_inbox = Mailbox.get(email);

    assertFalse(user_inbox.isEmpty());

    Message confirmation = user_inbox.get(0);
    assertEquals("User Account Confirmation: " + email, confirmation.getSubject());

    String token = getTokenFromMessage(confirmation);
    logger.info(token);

    ActivationState state =
        setup.getMgmtSvc().handleConfirmationTokenForAdminUser(org_owner.owner.getUuid(), token);
    assertEquals(ActivationState.CONFIRMED_AWAITING_ACTIVATION, state);

    confirmation = user_inbox.get(1);
    String body =
        ((MimeMultipart) confirmation.getContent()).getBodyPart(0).getContent().toString();
    Boolean subbedEmailed = StringUtils.contains(body, "$");

    assertFalse(subbedEmailed);

    assertEquals("User Account Confirmed", confirmation.getSubject());

    List<Message> sysadmin_inbox = Mailbox.get("*****@*****.**");
    assertFalse(sysadmin_inbox.isEmpty());

    Message activation = sysadmin_inbox.get(0);
    assertEquals("Request For Admin User Account Activation " + email, activation.getSubject());

    token = getTokenFromMessage(activation);
    logger.info(token);

    state = setup.getMgmtSvc().handleActivationTokenForAdminUser(org_owner.owner.getUuid(), token);
    assertEquals(ActivationState.ACTIVATED, state);

    Message activated = user_inbox.get(2);
    assertEquals("User Account Activated", activated.getSubject());

    MockImapClient client = new MockImapClient("mockserver.com", "test-user-2", "somepassword");
    client.processMail();
  }
コード例 #12
0
  @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;
  }
コード例 #13
0
 public Classifier(Message message) throws MessagingException {
   subject = message.getSubject();
   try {
     text = getRawText(message.getContent());
   } catch (IOException e) {
     throw (new MessagingException(
         "Unable to extract message body. [" + e.getClass().getName() + "] " + e.getMessage()));
   }
 }
コード例 #14
0
  /** Method for checking if the message has attachments. */
  public boolean hasAttachments() throws java.io.IOException, MessagingException {
    boolean hasAttachments = false;
    if (message.isMimeType("multipart/*")) {
      Multipart mp = (Multipart) message.getContent();
      if (mp.getCount() > 1) hasAttachments = true;
    }

    return hasAttachments;
  }
コード例 #15
0
 /** Returns the body of the message (if it's plain text). */
 public String getBody() throws MessagingException, java.io.IOException {
   Object content = message.getContent();
   if (message.isMimeType("text/plain")) {
     return (String) content;
   } else if (message.isMimeType("multipart/alternative")) {
     Multipart mp = (Multipart) message.getContent();
     int numParts = mp.getCount();
     for (int i = 0; i < numParts; ++i) {
       if (mp.getBodyPart(i).isMimeType("text/plain"))
         return (String) mp.getBodyPart(i).getContent();
     }
     return "";
   } else if (message.isMimeType("multipart/*")) {
     Multipart mp = (Multipart) content;
     if (mp.getBodyPart(0).isMimeType("text/plain"))
       return (String) mp.getBodyPart(0).getContent();
     else return "";
   } else return "";
 }
コード例 #16
0
ファイル: GetMail.java プロジェクト: 4mail/4mail_client
 // 读取邮件内容
 @SuppressWarnings({"rawtypes", "unchecked"})
 public Map readMail(String id) throws Exception {
   Map map = new HashMap();
   // 找到目标邮件
   Message readmsg = findMail(msg, id);
   // 读取邮件标题
   map.put("subject", readmsg.getSubject());
   // 读取发件人
   map.put("sender", MimeUtility.decodeText(readmsg.getFrom()[0].toString()));
   map.put("attach", "");
   // 取得邮件内容
   if (readmsg.isMimeType("text/*")) {
     map.put("content", readmsg.getContent().toString());
   } else {
     System.out.println("this is not a text mail");
     Multipart mp = (Multipart) readmsg.getContent();
     if (mp == null) {
       System.out.println("the content is null");
     } else System.out.println("--------------------------multipart:" + mp.toString());
     BodyPart part = null;
     String disp = null;
     StringBuffer result = new StringBuffer();
     // 遍历每个Miltipart对象
     for (int j = 0; j < mp.getCount(); j++) {
       part = mp.getBodyPart(j);
       disp = part.getDisposition();
       // 如果有附件
       if (disp != null && (disp.equals(Part.ATTACHMENT) || disp.equals(Part.INLINE))) {
         // 取得附件文件名
         String filename = MimeUtility.decodeText(part.getFileName()); // 解决中文附件名的问题
         map.put("attach", filename);
         // 下载附件
         InputStream in = part.getInputStream(); // 附件输入流
         if (attachFile.isDownload(filename)) attachFile.choicePath(filename, in); // // 下载附件
       } else {
         // 显示复杂邮件正文内容
         result.append(getPart(part, j, 1));
       }
     }
     map.put("content", result.toString());
   }
   return map;
 }
コード例 #17
0
 private void mailReceiver(Message msg) throws Exception {
   // 发件人信息
   Address[] froms = msg.getFrom();
   if (froms != null) {
     // System.out.println("发件人信息:" + froms[0]);
     InternetAddress addr = (InternetAddress) froms[0];
     System.out.println("发件人地址:" + addr.getAddress());
     System.out.println("发件人显示名:" + addr.getPersonal());
   }
   System.out.println("邮件主题:" + msg.getSubject());
   // getContent() 是获取包裹内容, Part相当于外包装
   Object o = msg.getContent();
   if (o instanceof Multipart) {
     Multipart multipart = (Multipart) o;
     reMultipart(multipart);
   } else if (o instanceof Part) {
     Part part = (Part) o;
     rePart(part);
   } else {
     System.out.println("类型" + msg.getContentType());
     System.out.println("内容" + msg.getContent());
   }
 }
コード例 #18
0
ファイル: MailImport.java プロジェクト: gineer01/jgnucashlib
 /**
  * @param aMessage the message to read
  * @return the content if it is of content-type "text/*"
  * @throws IOException may happen in reading
  * @throws MessagingException if we cannot fetch the content of the messsag
  */
 private String readTextContent(final Message aMessage) throws IOException, MessagingException {
   Object content = aMessage.getContent();
   if (content instanceof InputStream) {
     // TODO: charset
     InputStreamReader reader = new InputStreamReader((InputStream) content);
     StringBuilder sb = new StringBuilder();
     char[] buffer = new char[Byte.MAX_VALUE];
     int reat = 0;
     while ((reat = reader.read(buffer)) > 0) {
       sb.append(buffer, 0, reat);
     }
     return sb.toString();
   }
   return content.toString();
 }
コード例 #19
0
  /**
   * Retrieve message from retriever and check the body content
   *
   * @param retriever Retriever to read from
   * @param to Account to retrieve
   */
  private void retrieveAndCheckBody(Retriever retriever, String to)
      throws MessagingException, IOException {
    Message[] messages = retriever.getMessages(to);
    assertEquals(1, messages.length);
    Message message = messages[0];
    assertTrue(message.getContentType().equalsIgnoreCase("application/blubb"));

    // Check content
    InputStream contentStream = (InputStream) message.getContent();
    byte[] bytes = IOUtils.toByteArray(contentStream);
    assertArrayEquals(createLargeByteArray(), bytes);

    // Dump complete mail message. This leads to a FETCH command without section or "len" specified.
    message.writeTo(new ByteArrayOutputStream());
  }
コード例 #20
0
 /**
  * Saves all attachments to a temp directory, and returns the directory path. Null if no
  * attachments.
  */
 public File saveAttachments(Message message) throws IOException, MessagingException {
   File tmpDir = Files.createTempDir();
   boolean foundAttachments = false;
   Object content = message.getContent();
   if (message.isMimeType(MULTIPART_WILDCARD) && content instanceof Multipart) {
     Multipart mp = (Multipart) content;
     for (int i = 0; i < mp.getCount(); i++) {
       BodyPart bodyPart = mp.getBodyPart(i);
       if (bodyPart instanceof MimeBodyPart && isNotBlank(bodyPart.getFileName())) {
         MimeBodyPart mimeBodyPart = (MimeBodyPart) bodyPart;
         mimeBodyPart.saveFile(new File(tmpDir, mimeBodyPart.getFileName()));
         foundAttachments = true;
       }
     }
   }
   return foundAttachments ? tmpDir : null;
 }
コード例 #21
0
 /** Creates a new instance of RenderablePlainText */
 public RenderablePlainText(Message message) throws MessagingException, IOException {
   subject = message.getSubject();
   bodytext = (String) message.getContent();
   receivedOn = message.getReceivedDate();
   if (!StringUtils.isNull(bodytext)) {
     if (bodytext.indexOf("Original Message") > -1) {
       subBody = bodytext.substring(0, bodytext.indexOf("Original Message"));
     }
     if (!StringUtils.isNull(bodytext)
         && bodytext.indexOf(", \"[email protected]\" <*****@*****.**> wrote:") > -1) {
       String tempstr =
           bodytext.substring(
               0, bodytext.indexOf(", \"[email protected]\" <*****@*****.**> wrote:"));
       subBody = tempstr.substring(0, tempstr.lastIndexOf("On"));
     }
   }
 }
コード例 #22
0
  private Message[] getMessages(String host, String user, String password)
      throws MessagingException, IOException {

    Session session = Session.getDefaultInstance(new Properties());
    Store store = session.getStore("imap");
    store.connect(host, user, password);

    Folder folder = store.getFolder("inbox");
    folder.open(Folder.READ_ONLY);
    Message[] msgs = folder.getMessages();

    for (Message m : msgs) {
      logger.info("Subject: " + m.getSubject());
      logger.info("Body content 0 " + ((MimeMultipart) m.getContent()).getBodyPart(0).getContent());
      logger.info("Body content 1 " + ((MimeMultipart) m.getContent()).getBodyPart(1).getContent());
    }
    return msgs;
  }
コード例 #23
0
  /**
   * Retrieve message from retriever and check the attachment and text content
   *
   * @param retriever Retriever to read from
   * @param to Account to retrieve
   */
  private void retrieveAndCheck(Retriever retriever, String to)
      throws MessagingException, IOException {
    Message[] messages = retriever.getMessages(to);
    assertEquals(1, messages.length);
    Message message = messages[0];
    assertTrue(message.getContentType().startsWith("multipart/mixed"));
    MimeMultipart body = (MimeMultipart) message.getContent();
    assertTrue(body.getContentType().startsWith("multipart/mixed"));
    assertEquals(2, body.getCount());

    // Message text
    final BodyPart textPart = body.getBodyPart(0);
    String text = (String) textPart.getContent();
    assertEquals(createLargeString(), text);

    final BodyPart attachment = body.getBodyPart(1);
    assertTrue(attachment.getContentType().equalsIgnoreCase("application/blubb; name=file"));
    InputStream attachmentStream = (InputStream) attachment.getContent();
    byte[] bytes = IOUtils.toByteArray(attachmentStream);
    assertArrayEquals(createLargeByteArray(), bytes);
  }
コード例 #24
0
 @Test
 public void should_receive_email_if_user_has_lost_his_password() throws Exception {
   String email = randomEmail();
   DomainUser domainUser =
       userService.create(new DomainUser(randomString(), email, randomString()));
   LostPasswordData token =
       userService.sendLostPasswordMail(domainUser.getEmail(), Locale.ENGLISH);
   Message message = getMessage(token.getEmail());
   assertThat(message.getSubject()).isEqualTo("[Junit] Please reset your password");
   assertThat(message.getContent().toString())
       .isEqualTo(
           "Ho, you lost your Junit password. no problemo!\n"
               + "\n"
               + "Use the following link within the next 24 hours to reset your password:\n"
               + "\n"
               + "/#retrievePage?token="
               + token.getToken()
               + "\n"
               + "\n"
               + "Thanks,\n"
               + "the team");
 }
コード例 #25
0
  public static void receberEmailPop() {

    try {

      System.out.println();
      System.out.println("LENDO EMAILS POP...");

      // Verifica qual tipo de provider, se é imap , ou pop/pop3

      ClienteEmailCentralServicoDao clienteEmail = new ClienteEmailCentralServicoDao();
      Message mensagens[] = clienteEmail.getEmail2s();

      MimeMultipart mmp = new MimeMultipart();
      MimeBodyPart mbp1 = new MimeBodyPart();
      MimeBodyPart mbp2 = new MimeBodyPart();

      int contador = 0;
      for (Message message : mensagens) {
        if (!message.isSet(Flags.Flag.SEEN)) {

          String solicitacao = message.getSubject();

          boolean encontrar = solicitacao.matches(".*Solicitação.*");
          /**
           * Verifica se no título do email existe a palavra Solicitação e o número, caso exista,
           * ele vai vincular o email a solicitacao do titulo,
           */
          if (encontrar) {

            encontrar = solicitacao.matches(".*[0-9].*");
            /**
             * Verifica se no título do email possui valor numérico, se possuir, prossegue, senão,
             * encerra
             */
            if (encontrar) {

              /**
               * Retira tudo o que não for numérico, pega os numeros e usa como id da solicitacao de
               * servico
               */
              solicitacao = solicitacao.replaceAll("[^0-9]", "");

              mmp = (MimeMultipart) message.getContent();
              mbp1 = (MimeBodyPart) mmp.getBodyPart(0);
              mbp2 = (MimeBodyPart) mmp.getBodyPart(1);

              System.out.println(
                  "-----------------------------------------------------------------------");
              System.out.println("CONTEÚDO DO EMAIL :" + mbp1.getContent());
              System.out.println("TITULO DO EMAIL : " + message.getSubject());
              System.out.println(
                  "-----------------------------------------------------------------------");
              System.out.println("Contador : " + contador);
              contador++;
              System.out.println();
              System.out.println();
              System.out.println();

              String minutoFormatado = "";

              OcorrenciaSolicitacaoDTO ocorrenciaDto = new OcorrenciaSolicitacaoDTO();
              OcorrenciaSolicitacaoService ocorrenciaService =
                  (OcorrenciaSolicitacaoService)
                      ServiceLocator.getInstance()
                          .getService(OcorrenciaSolicitacaoService.class, null);
              ocorrenciaDto.setIdSolicitacaoServico(Integer.parseInt(solicitacao));
              Calendar calendar = Calendar.getInstance();
              int hora = calendar.get(Calendar.HOUR_OF_DAY);
              int minuto = calendar.get(Calendar.MINUTE);
              ocorrenciaDto.setDataregistro(UtilDatas.getSqlDate(new java.util.Date()));
              if (minuto < 10) {
                minutoFormatado = "0" + String.valueOf(minuto);
                ocorrenciaDto.setHoraregistro(hora + ":" + minuto);
              } else {
                ocorrenciaDto.setHoraregistro(hora + ":" + minuto);
              }

              ocorrenciaDto.setRegistradopor("Email - Automatico");
              ocorrenciaDto.setDescricao(message.getSubject().toString());
              ocorrenciaDto.setOcorrencia(mbp1.getContent().toString());
              SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
              java.sql.Date dataFormatada = UtilDatas.getSqlDate(message.getReceivedDate());
              ocorrenciaDto.setDataregistro(UtilDatas.getSqlDate(new java.util.Date()));
              String data = UtilDatas.formatHoraFormatadaHHMMSSStr(message.getReceivedDate());
              ocorrenciaService.create(ocorrenciaDto);
            }
          }
        }
      }

      System.out.println("THREAD FINALIZADA!!!---------------------");

    } catch (Exception e) {
      System.out.println("###########################################");
      System.out.println("Erro ao executar a Thread");
      System.out.println("###########################################");
      e.printStackTrace();
    }
  }
コード例 #26
0
  public ClienteEmailCentralServicoDTO readMessage(
      DocumentHTML document,
      HttpServletRequest request,
      HttpServletResponse response,
      String messageId)
      throws Exception {
    ClienteEmailCentralServicoDTO clienteEmailCentralServicoDto =
        new ClienteEmailCentralServicoDTO();
    clienteEmailCentralServicoDto.setResultSucess(true);

    try {
      if (CONEXAO_EMAIL_SERVIDOR.equals("")
          || CONEXAO_EMAIL_PROVIDER.equals("")
          || CONEXAO_EMAIL_CAIXA.equals("")
          || CONEXAO_EMAIL_SENHA.equals("")
          || CONEXAO_EMAIL_PASTA.equals("")) {
        clienteEmailCentralServicoDto.setResultSucess(false);
        clienteEmailCentralServicoDto.setResultMessage(
            UtilI18N.internacionaliza(
                request, "clienteEmailCentralServico.problemasRealizarleituraEmailsParametros"));
      } else {
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", CONEXAO_EMAIL_PROVIDER);

        props.setProperty("mail.imaps.auth.plain.disable", "true");
        props.setProperty("mail.imaps.ssl.trust", "*");
        // props.setProperty("mail.debug", "true");

        if (!CONEXAO_EMAIL_PORTA.equals(""))
          props.setProperty("mail." + CONEXAO_EMAIL_PROVIDER + ".port", CONEXAO_EMAIL_PORTA);

        Session session = Session.getInstance(props, null);
        Store store = session.getStore();
        store.connect(CONEXAO_EMAIL_SERVIDOR, CONEXAO_EMAIL_CAIXA, CONEXAO_EMAIL_SENHA);

        Folder inbox = store.getFolder(CONEXAO_EMAIL_PASTA);
        inbox.open(Folder.READ_WRITE);

        SearchTerm searchTerm = new MessageIDTerm(messageId);
        Message[] messages = inbox.search(searchTerm);

        if (messages != null && messages.length > 0) {
          ArrayList<ClienteEmailCentralServicoMessagesDTO> emailMessages =
              new ArrayList<ClienteEmailCentralServicoMessagesDTO>();
          for (Message message : messages) {
            ClienteEmailCentralServicoMessagesDTO clienteEmailMessagesDto =
                new ClienteEmailCentralServicoMessagesDTO();

            MimeMessage m = (MimeMessage) inbox.getMessage(message.getMessageNumber());
            clienteEmailMessagesDto.setMessageId(m.getMessageID());
            clienteEmailMessagesDto.setMessageNumber(message.getMessageNumber());

            Address[] in = message.getFrom();
            clienteEmailMessagesDto.setMessageEmail(
                (in == null ? null : ((InternetAddress) in[0]).getAddress()));

            clienteEmailMessagesDto.setMessageSubject(message.getSubject());
            clienteEmailMessagesDto.setMessageReceivedDate(message.getReceivedDate());
            clienteEmailMessagesDto.setSeen(message.isSet(Flags.Flag.SEEN));

            Object objRef = message.getContent();
            String content = "";

            if (!(objRef instanceof Multipart)) {
              content = (String) message.getContent();
            } else {
              Multipart mp = (Multipart) message.getContent();
              BodyPart bp = mp.getBodyPart(0);

              content = getContent(bp);
            }

            if (content != null) {
              // content = content.replaceAll("(\r\n|\r|\n)", "<br />");
              content = StringEscapeUtils.escapeEcmaScript(content);

              clienteEmailMessagesDto.setMessageContent(content);
            }

            emailMessages.add(clienteEmailMessagesDto);
          }

          clienteEmailCentralServicoDto.setEmailMessages(emailMessages);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      clienteEmailCentralServicoDto.setResultSucess(false);
      clienteEmailCentralServicoDto.setResultMessage(
          UtilI18N.internacionaliza(
              request, "clienteEmailCentralServico.problemasRealizarleituraEmails"));
    }

    return clienteEmailCentralServicoDto;
  }
コード例 #27
0
  /**
   * Aggregates the e-mail message by reading it and turning it either into a page or a file upload.
   *
   * @param message the e-mail message
   * @param site the site to publish to
   * @throws MessagingException if fetching the message data fails
   * @throws IOException if writing the contents to the output stream fails
   */
  protected Page aggregate(Message message, Site site)
      throws IOException, MessagingException, IllegalArgumentException {

    ResourceURI uri = new PageURIImpl(site, UUID.randomUUID().toString());
    Page page = new PageImpl(uri);
    Language language = site.getDefaultLanguage();

    // Extract title and subject. Without these two, creating a page is not
    // feasible, therefore both messages throw an IllegalArgumentException if
    // the fields are not present.
    String title = getSubject(message);
    String author = getAuthor(message);

    // Collect default settings
    PageTemplate template = site.getDefaultTemplate();
    if (template == null)
      throw new IllegalStateException("Missing default template in site '" + site + "'");
    String stage = template.getStage();
    if (StringUtils.isBlank(stage))
      throw new IllegalStateException(
          "Missing stage definition in template '" + template.getIdentifier() + "'");

    // Standard fields
    page.setTitle(title, language);
    page.setTemplate(template.getIdentifier());
    page.setPublished(new UserImpl(site.getAdministrator()), message.getReceivedDate(), null);

    // TODO: Translate e-mail "from" into site user and throw if no such
    // user can be found
    page.setCreated(site.getAdministrator(), message.getSentDate());

    // Start looking at the message body
    String contentType = message.getContentType();
    if (StringUtils.isBlank(contentType))
      throw new IllegalArgumentException("Message content type is unspecified");

    // Text body
    if (contentType.startsWith("text/plain")) {
      // TODO: Evaluate charset
      String body = null;
      if (message.getContent() instanceof String) body = (String) message.getContent();
      else if (message.getContent() instanceof InputStream)
        body = IOUtils.toString((InputStream) message.getContent());
      else throw new IllegalArgumentException("Message body is of unknown type");
      return handleTextPlain(body, page, language);
    }

    // HTML body
    if (contentType.startsWith("text/html")) {
      // TODO: Evaluate charset
      return handleTextHtml((String) message.getContent(), page, null);
    }

    // Multipart body
    else if ("mime/multipart".equalsIgnoreCase(contentType)) {
      Multipart mp = (Multipart) message.getContent();
      for (int i = 0, n = mp.getCount(); i < n; i++) {
        Part part = mp.getBodyPart(i);
        String disposition = part.getDisposition();
        if (disposition == null) {
          MimeBodyPart mbp = (MimeBodyPart) part;
          if (mbp.isMimeType("text/plain")) {
            return handleTextPlain((String) mbp.getContent(), page, null);
          } else {
            // TODO: Implement special non-attachment cases here of
            // image/gif, text/html, ...
            throw new UnsupportedOperationException(
                "Multipart message bodies of type '"
                    + mbp.getContentType()
                    + "' are not yet supported");
          }
        } else if (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE)) {
          logger.info("Skipping message attachment " + part.getFileName());
          // saveFile(part.getFileName(), part.getInputStream());
        }
      }

      throw new IllegalArgumentException(
          "Multipart message did not contain any recognizable content");
    }

    // ?
    else {
      throw new IllegalArgumentException("Message body is of unknown type '" + contentType + "'");
    }
  }
コード例 #28
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";
  }
コード例 #29
0
  /**
   * Tests that when a user is added to an app and activation on that app is required, the org admin
   * is emailed
   *
   * @throws Exception
   *     <p>TODO, I'm not convinced this worked correctly. IT can't find users collection in the
   *     orgs. Therefore, I think this is a legitimate bug that was just found from fixing the tests
   *     to be unique admins orgs and emails
   */
  @Test
  public void testAppUserActivationResetpwdMail() throws Exception {

    final String orgName = uniqueOrg();
    final String appName = uniqueApp();
    final String adminUserName = uniqueUsername();
    final String adminEmail = uniqueEmail();
    final String adminPasswd = "testpassword";

    OrganizationOwnerInfo orgOwner =
        createOwnerAndOrganization(
            orgName, appName, adminUserName, adminEmail, adminPasswd, false, false);
    assertNotNull(orgOwner);

    ApplicationInfo app =
        setup.getMgmtSvc().createApplication(orgOwner.getOrganization().getUuid(), appName);
    this.app.refreshIndex();

    // turn on app admin approval for app users
    enableAdminApproval(app.getId());

    final String appUserUsername = uniqueUsername();
    final String appUserEmail = uniqueEmail();

    OrganizationConfig orgConfig =
        setup.getMgmtSvc().getOrganizationConfigByUuid(orgOwner.getOrganization().getUuid());

    User appUser = setupAppUser(app.getId(), appUserUsername, appUserEmail, false);

    String subject = "Request For User Account Activation " + appUserEmail;
    String activation_url =
        orgConfig.getFullUrl(
            WorkflowUrl.USER_ACTIVATION_URL, orgName, appName, appUser.getUuid().toString());

    setup.refreshIndex(app.getId());

    // Activation
    setup.getMgmtSvc().startAppUserActivationFlow(app.getId(), appUser);

    List<Message> inbox = Mailbox.get(adminEmail);
    assertFalse(inbox.isEmpty());
    MockImapClient client = new MockImapClient("usergrid.com", adminUserName, "somepassword");
    client.processMail();

    // subject ok
    Message activation = inbox.get(0);
    assertEquals(subject, activation.getSubject());

    // activation url ok
    String mailContent =
        (String) ((MimeMultipart) activation.getContent()).getBodyPart(1).getContent();
    logger.info(mailContent);
    assertTrue(StringUtils.contains(mailContent.toLowerCase(), activation_url.toLowerCase()));

    // token ok
    String token = getTokenFromMessage(activation);
    logger.info(token);
    ActivationState activeState =
        setup.getMgmtSvc().handleActivationTokenForAppUser(app.getId(), appUser.getUuid(), token);
    assertEquals(ActivationState.ACTIVATED, activeState);

    subject = "Password Reset";
    String reset_url =
        orgConfig.getFullUrl(
            WorkflowUrl.USER_RESETPW_URL, orgName, appName, appUser.getUuid().toString());

    // reset_pwd
    setup.getMgmtSvc().startAppUserPasswordResetFlow(app.getId(), appUser);

    inbox = Mailbox.get(appUserEmail);
    assertFalse(inbox.isEmpty());
    client = new MockImapClient("test.com", appUserUsername, "somepassword");
    client.processMail();

    // subject ok
    Message reset = inbox.get(1);
    assertEquals(subject, reset.getSubject());

    // resetpwd url ok
    mailContent = (String) ((MimeMultipart) reset.getContent()).getBodyPart(1).getContent();
    logger.info(mailContent);
    assertTrue(StringUtils.contains(mailContent.toLowerCase(), reset_url.toLowerCase()));

    // token ok
    token = getTokenFromMessage(reset);
    logger.info(token);
    assertTrue(
        setup
            .getMgmtSvc()
            .checkPasswordResetTokenForAppUser(app.getId(), appUser.getUuid(), token));

    // ensure revoke works
    setup.getMgmtSvc().revokeAccessTokenForAppUser(token);
    assertFalse(
        setup
            .getMgmtSvc()
            .checkPasswordResetTokenForAppUser(app.getId(), appUser.getUuid(), token));
  }
コード例 #30
0
  /** Tests to make sure a normal user must be activated by the admin after confirmation. */
  @Test
  public void testAppUserConfirmationMail() throws Exception {
    final String orgName = uniqueOrg();
    final String appName = uniqueApp();
    final String userName = uniqueUsername();
    final String email = uniqueEmail();
    final String passwd = "testpassword";

    OrganizationOwnerInfo orgOwner;

    orgOwner = createOwnerAndOrganization(orgName, appName, userName, email, passwd, false, false);
    assertNotNull(orgOwner);

    setup.getEntityIndex().refresh(app.getId());

    ApplicationInfo app =
        setup.getMgmtSvc().createApplication(orgOwner.getOrganization().getUuid(), appName);
    setup.refreshIndex(app.getId());
    assertNotNull(app);
    enableEmailConfirmation(app.getId());
    enableAdminApproval(app.getId());

    setup.getEntityIndex().refresh(app.getId());

    final String appUserEmail = uniqueEmail();
    final String appUserUsername = uniqueUsername();

    User user = setupAppUser(app.getId(), appUserUsername, appUserEmail, true);

    OrganizationConfig orgConfig =
        setup.getMgmtSvc().getOrganizationConfigByUuid(orgOwner.getOrganization().getUuid());

    String subject = "User Account Confirmation: " + appUserEmail;
    String confirmation_url =
        orgConfig.getFullUrl(
            WorkflowUrl.USER_CONFIRMATION_URL, orgName, appName, user.getUuid().toString());

    // request confirmation
    setup.getMgmtSvc().startAppUserActivationFlow(app.getId(), user);

    List<Message> inbox = Mailbox.get(appUserEmail);
    assertFalse(inbox.isEmpty());
    MockImapClient client = new MockImapClient("test.com", appUserUsername, "somepassword");
    client.processMail();

    // subject ok
    Message confirmation = inbox.get(0);
    assertEquals(subject, confirmation.getSubject());

    // confirmation url ok
    String mailContent =
        (String) ((MimeMultipart) confirmation.getContent()).getBodyPart(1).getContent();
    logger.info(mailContent);
    assertTrue(StringUtils.contains(mailContent.toLowerCase(), confirmation_url.toLowerCase()));

    // token ok
    String token = getTokenFromMessage(confirmation);
    logger.info(token);
    ActivationState activeState =
        setup.getMgmtSvc().handleConfirmationTokenForAppUser(app.getId(), user.getUuid(), token);
    assertEquals(ActivationState.CONFIRMED_AWAITING_ACTIVATION, activeState);
  }