コード例 #1
0
  public static Date getDateFromMessage(Message message, Connection con) {

    Date result = null;

    try {
      if (hasHeader("Date", message)) {
        Date msg_date = message.getSentDate();
        // If Java Mail could not parse the date ...
        if (msg_date == null) {
          // see if the postgresql server can infer the date ...
          String datestr = message.getHeader("Date")[0];
          Main.getLogger()
              .debug(2, "Invalid Message date supplied - letting Postgresql guess: " + datestr);
          try {
            Statement st = con.createStatement();
            ResultSet r = st.executeQuery("SELECT TIMESTAMP WITH TIME ZONE '" + datestr + "'");
            if (r.next()) result = new Date(r.getTimestamp(1).getTime());
            r.close();
            st.close();
          } catch (SQLException e) {
            Main.getLogger()
                .debug(
                    2,
                    "Error asking PostgreSQL for the date - using default date. " + e.getMessage());
          }

        } else result = msg_date;
      }
      if (result == null && hasHeader("Received", message)) {
        Main.getLogger().debug(2, "No Message date supplied - trying to infer");
        String[] prtemp = message.getHeader("Received")[0].split(";");
        String datestr = (prtemp.length > 0 ? prtemp[prtemp.length - 1] : "");
        try {
          Statement st = con.createStatement();
          ResultSet r = st.executeQuery("SELECT TIMESTAMP WITH TIME ZONE '" + datestr + "'");
          if (r.next()) result = new Date(r.getTimestamp(1).getTime());
        } catch (SQLException e) {
          Main.getLogger()
              .debug(
                  2,
                  "Error asking PostgreSQL for the date - using default date. " + e.getMessage());
        }
      }
    } catch (MessagingException e) {
      Main.getLogger().error("Error while extracting the date", e);
    }

    // If nothing worked set default date
    if (result == null) {
      result = new Date(0);
    }

    return result;
  }
コード例 #2
0
ファイル: MailTest.java プロジェクト: TuWei1992/javawebmail
 @Test
 public void testFindMessageByIdBad() throws MessagingException {
   Folder f = mock(Folder.class);
   target.mFolder = f;
   Message m1 = mock(Message.class);
   Message m2 = mock(Message.class);
   Message m3 = mock(Message.class);
   when(m1.getHeader(MESSAGE_ID_HEADER)).thenReturn(new String[] {"bleah"});
   when(m2.getHeader(MESSAGE_ID_HEADER)).thenReturn(new String[] {"meh"});
   when(m3.getHeader(MESSAGE_ID_HEADER)).thenReturn(new String[] {"three"});
   when(f.getMessages()).thenReturn(new Message[] {m1, m2, m3});
   Message message = target.findMessageById(WANTED_MESSAGE_ID);
   assertNull(message);
 }
コード例 #3
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);
    }
  }
コード例 #4
0
ファイル: Eml.java プロジェクト: evanleonard/ilarkesto
 public static String getHeaderFieldValue(Message msg, String fieldName) {
   String[] header;
   try {
     header = msg.getHeader(fieldName);
   } catch (MessagingException ex) {
     throw new RuntimeException(ex);
   }
   if (header == null) return null;
   return header[0];
 }
コード例 #5
0
  public static void dumpEnvelope(Message m) throws Exception {
    pr("This is the message envelope");
    pr("---------------------------");
    Address[] a;
    // FROM
    if ((a = m.getFrom()) != null) {
      for (int j = 0; j < a.length; j++) pr("FROM: " + a[j].toString());
    }

    // TO
    if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
      for (int j = 0; j < a.length; j++) pr("TO: " + a[j].toString());
    }

    // SUBJECT
    pr("SUBJECT: " + m.getSubject());

    // DATE
    Date d = m.getSentDate();
    pr("SendDate: " + (d != null ? d.toString() : "UNKNOWN"));

    // FLAGS
    Flags flags = m.getFlags();
    StringBuffer sb = new StringBuffer();
    Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags

    boolean first = true;
    for (int i = 0; i < sf.length; i++) {
      String s;
      Flags.Flag f = sf[i];
      if (f == Flags.Flag.ANSWERED) s = "\\Answered";
      else if (f == Flags.Flag.DELETED) s = "\\Deleted";
      else if (f == Flags.Flag.DRAFT) s = "\\Draft";
      else if (f == Flags.Flag.FLAGGED) s = "\\Flagged";
      else if (f == Flags.Flag.RECENT) s = "\\Recent";
      else if (f == Flags.Flag.SEEN) s = "\\Seen";
      else continue; // skip it
      if (first) first = false;
      else sb.append(' ');
      sb.append(s);
    }

    String[] uf = flags.getUserFlags(); // get the user flag strings
    for (int i = 0; i < uf.length; i++) {
      if (first) first = false;
      else sb.append(' ');
      sb.append(uf[i]);
    }
    pr("FLAGS: " + sb.toString());

    // X-MAILER
    String[] hdrs = m.getHeader("X-Mailer");
    if (hdrs != null) pr("X-Mailer: " + hdrs[0]);
    else pr("X-Mailer NOT available");
  }
コード例 #6
0
  /**
   * Get message header for MailMessage.
   *
   * @param msg
   * @param mailMsg
   * @throws MessagingException
   */
  protected void processHeader(Message msg, MailMessage mailMsg) throws MessagingException {
    String xAutoResponseSuppressHeaderName = "X-Auto-Response-Suppress";
    String xAutoReplyHeaderName = "X-Autoreply";
    String xAutoRespondHeaderName = "X-Autorespond";
    String xAutoSubmittedHeaderName = "auto-submitted";

    String xAutoResponseSuppressVal =
        Arrays.toString(msg.getHeader(xAutoResponseSuppressHeaderName));
    String xAutoReplyVal = Arrays.toString(msg.getHeader(xAutoReplyHeaderName));
    String xAutoRespondVal = Arrays.toString(msg.getHeader(xAutoRespondHeaderName));
    String xAutoSubmittedVal = Arrays.toString(msg.getHeader(xAutoSubmittedHeaderName));
    String contentType = msg.getContentType();

    // If any of those are present in an email, then that email is an auto-reply.
    String[] autoReplyArray = {
      xAutoResponseSuppressVal, xAutoReplyVal, xAutoRespondVal, xAutoSubmittedVal
    };
    mailMsg.setAutoReply(autoReplyArray);
    mailMsg.setContentType(contentType);
  }
コード例 #7
0
  private static boolean hasHeader(String name, Message message) {

    String[] result;
    try {
      result = message.getHeader(name);
    } catch (MessagingException e) {
      return false;
    }
    if (result == null) return false;
    if (result.length == 0) return false;
    else return true;
  }
コード例 #8
0
ファイル: Eml.java プロジェクト: evanleonard/ilarkesto
 public static String getMessageId(Message msg) {
   String[] header;
   try {
     header = msg.getHeader(HEADER_MESSAGE_ID);
   } catch (MessagingException ex) {
     throw new RuntimeException(ex);
   }
   if (header == null) {
     LOG.debug("Message has no id.'");
     return null;
   }
   return header[0];
 }
コード例 #9
0
ファイル: MBUtil.java プロジェクト: JamesLefeu/liferay-portal
  public static String getParentMessageIdString(Message message) throws Exception {

    // If the previous block failed, try to get the parent message ID from
    // the "References" header as explained in
    // http://cr.yp.to/immhf/thread.html. Some mail clients such as Yahoo!
    // Mail use the "In-Reply-To" header, so we check that as well.

    String parentHeader = null;

    String[] references = message.getHeader("References");

    if (ArrayUtil.isNotEmpty(references)) {
      String reference = references[0];

      int x = reference.lastIndexOf("<mb.");

      if (x > -1) {
        int y = reference.indexOf(">", x);

        parentHeader = reference.substring(x, y);
      }
    }

    if (parentHeader == null) {
      String[] inReplyToHeaders = message.getHeader("In-Reply-To");

      if (ArrayUtil.isNotEmpty(inReplyToHeaders)) {
        parentHeader = inReplyToHeaders[0];
      }
    }

    if (Validator.isNull(parentHeader) || !parentHeader.startsWith(MESSAGE_POP_PORTLET_PREFIX, 1)) {

      parentHeader = _getParentMessageIdFromSubject(message);
    }

    return parentHeader;
  }
コード例 #10
0
 /**
  * Method getHeader answers a List of all of the headers in the receiver whose name is equal to
  * the passed name. If no headers are found an empty List is returned.
  *
  * @param name
  * @return <code>List</code> not null, possibly empty
  * @throws SieveMailException
  */
 @SuppressWarnings("unchecked")
 public List<String> getHeader(String name) throws SieveMailException {
   List<String> result = Collections.EMPTY_LIST;
   if (mail != null) {
     try {
       String[] values = mail.getHeader(name);
       if (values != null) {
         result = Arrays.asList(values);
       }
     } catch (MessagingException e) {
       throw new SieveMailException(e);
     }
   }
   return result;
 }
コード例 #11
0
ファイル: MBUtil.java プロジェクト: JamesLefeu/liferay-portal
  public static boolean hasMailIdHeader(Message message) throws Exception {
    String[] messageIds = message.getHeader("Message-ID");

    if (messageIds == null) {
      return false;
    }

    for (String messageId : messageIds) {
      if (Validator.isNotNull(PropsValues.POP_SERVER_SUBDOMAIN)
          && messageId.contains(PropsValues.POP_SERVER_SUBDOMAIN)) {

        return true;
      }
    }

    return false;
  }
コード例 #12
0
  /**
   * Using the first 'X-Priority' from the message, get the issue's priority
   *
   * @param message message
   * @return message priority
   * @throws MessagingException if cannot read message's header
   */
  private String getPriority(Message message) throws MessagingException {
    String[] xPrioHeaders = message.getHeader("X-Priority");

    if (xPrioHeaders != null && xPrioHeaders.length > 0) {
      String xPrioHeader = xPrioHeaders[0];

      int priorityValue = Integer.parseInt(TextUtils.extractNumber(xPrioHeader));

      if (priorityValue == 0) {
        return getDefaultSystemPriority();
      }

      // if priority is unset - pick the closest priority, this should be a sensible default
      Collection<Priority> priorities = getConstantsManager().getPriorityObjects();

      Iterator<Priority> priorityIt = priorities.iterator();

      /*
       * NOTE: Valid values for X-priority are (1=Highest, 2=High, 3=Normal, 4=Low & 5=Lowest) The X-Priority
       * (priority in email header) is divided by 5 (number of valid values) this gives the percentage
       * representation of the priority. We multiply this by the priority.size() (number of priorities in jira) to
       * scale and map the percentage to a priority in jira.
       */
      int priorityNumber =
          (int) Math.ceil(((double) priorityValue / 5d) * (double) priorities.size());
      // if priority is too large, assume its the 'lowest'
      if (priorityNumber > priorities.size()) {
        priorityNumber = priorities.size();
      }

      String priority = null;

      for (int i = 0; i < priorityNumber; i++) {
        priority = priorityIt.next().getId();
      }

      return priority;
    } else {
      return getDefaultSystemPriority();
    }
  }
コード例 #13
0
 private static boolean verifiedByAddress(
     Connection connection,
     Message msg,
     String msgId,
     String key,
     String userId,
     String subject,
     String body)
     throws MessagingException, HttpException, SQLException, IOException {
   log("Testing autoverify.");
   String addrs[] = msg.getHeader("To");
   for (int i = 0; i < addrs.length; i++) {
     InternetAddress address = new InternetAddress(addrs[i]);
     String to = address.getAddress();
     String verify = getVerificationPhrase(to);
     log("Autoverify to: " + to + " -> secret phrase=" + verify);
     if (verify != null) {
       return autoVerify(msg, connection, verify, msgId, key, userId, subject, body);
     }
   }
   return false;
 }
コード例 #14
0
ファイル: MailUtils.java プロジェクト: alathon/mailman
  /**
   * Creates a Mail
   *
   * @param inboxHelper
   * @param message
   * @param mUId
   * @return
   * @throws FolderClosedException
   * @throws MessagingException
   * @throws IOException
   */
  public static RawMail createMail(Message message) throws FolderClosedException {
    try {
      // fill the message objects with messagedata
      String[] fromInfo = MailUtils.getFromInfo(message.getFrom());

      if (fromInfo[0] == null || fromInfo[0].isEmpty()) {
        fromInfo = MailUtils.getFromInfo(message.getReplyTo());
      }
      if (fromInfo[0] == null || fromInfo[0].isEmpty()) {
        String[] returnPath = message.getHeader("Return-Path");
        if (returnPath.length > 0) {
          fromInfo[0] = returnPath[0].trim();
          if (fromInfo[0].charAt(0) == '<') fromInfo[0].substring(1);
          if (fromInfo[0].charAt(fromInfo[0].length() - 1) == '>')
            fromInfo[0].substring(0, fromInfo[0].length() - 2);
        }
      }

      String mFromAddress = (fromInfo[0] != null) ? fromInfo[0] : "";
      RawMail mail = new RawMail();
      // Note: Mail ids are generated based on contents - do not set an id

      String mSubject = message.getSubject();
      mail.setSubject(mSubject);
      mail.setFrom(new EmailAddress(mFromAddress, fromInfo[1]));
      mail.setCreated(new Date());

      // Prevent evil mail servers from sending from the future
      Date now = new Date();
      Date sentDate = message.getSentDate();
      Date recDate = message.getReceivedDate();

      if (sentDate == null || now.before(sentDate)) sentDate = new Date();
      if (recDate == null || now.before(recDate)) recDate = new Date();

      mail.setSentDate(sentDate);
      mail.setRecievedDate(recDate);

      mail.setServerId(String.valueOf(message.getMessageNumber()));

      try {
        mail.setBody(MailUtils.getBody(message));
      } catch (Throwable ex) {
        System.out.println("Failed when reading mail body");
      }

      // Headers
      Enumeration<?> allHeaders = message.getAllHeaders();
      HashMap<String, String> mailHeaders = new HashMap<String, String>();
      while (allHeaders.hasMoreElements()) {
        Header header = (Header) allHeaders.nextElement();
        mailHeaders.put(header.getName(), header.getValue());
      }
      mail.setHeaders(mailHeaders);

      try {
        mail.setRecipients(MailUtils.getRecipients(Message.RecipientType.TO, message));
      } catch (Throwable ex) {
        System.out.println("Throwable during setRecipients");
      }
      try {
        mail.setRecipients(MailUtils.getRecipients(Message.RecipientType.CC, message));
      } catch (Throwable ex) {
        System.out.println("Throwable during setRecipients");
      }
      try {
        mail.setRecipients(MailUtils.getRecipients(Message.RecipientType.BCC, message));
      } catch (Throwable ex) {
        System.out.println("Throwable during setRecipients");
      }
      return mail;
    } catch (FolderClosedException ex) {
      throw ex;
    } catch (Throwable ex) {
      System.out.println("Could not read mail");
    }
    return null;
  }
コード例 #15
0
  public static void main(String[] args) {

    try {

      Class.forName("com.mysql.jdbc.Driver");
      properties.load(new FileInputStream("parser.properties"));

      // FileInputStream reader = new FileInputStream("msg.txt");
      // Message msg = new MimeMessage(Session.getInstance(new Properties()), reader);
      Message msg = new MimeMessage(Session.getInstance(new Properties()), System.in);

      log("Message parsed.");
      String[] refs = msg.getHeader("In-Reply-To");
      String[] refsBackup = msg.getHeader("References");
      String subject = msg.getSubject();
      String body;
      if ((body = getBody(msg)) != null) {
        String[] references = parseReferences(refs);
        if (references == null || !valid(references)) {
          log("Reference not found in header field In-Reply-To. Trying references.");
          references = parseReferences(refsBackup);
        }
        if (references == null) {
          replayError(
              msg,
              subject,
              body,
              "Your email could not be posted due to internal error. Please contact support. Error: NO REFERENCS DEFINED.");
        }
        if (references.length != 6 && references.length != 3) {
          replayError(
              msg,
              subject,
              body,
              "Your email could not be posted due to internal error. Please contact support. Error: REFERENCS FORMAT ERROR.");
        }
        if (references[0].equals("post")) {
          String table = references[1];
          String userId = references[2];
          String msgId = references[3];
          String objectId = references[4];
          String threadId = references[5];
          post(msg, userId, msgId, table, objectId, threadId, subject, body);
        } else if (references[0].equals("verify")) {
          String msgId = references[1];
          String key = references[2];
          verify(msgId, key);
        } else {
          replayError(
              msg,
              subject,
              body,
              "Your email could not be posted due to internal error. Please contact support. Error: REFERENCS COMMAND.");
        }
      } else {
        // Error - currently only plain text!
        replayError(msg, subject, body, "Only plain text or html messages are supported.");
      }

      log("All done.");

    } catch (Exception e) {
      log("Error occured: " + e.getMessage());
      e.printStackTrace();
    }
  }