List of usage examples for javax.mail.internet MimeMessage getMessageID
public String getMessageID() throws MessagingException
From source file:net.wastl.webmail.server.WebMailSession.java
/** * Fetch a message from a folder.// w w w. ja va 2 s . c om * Will put the messages parameters in the sessions environment * * @param foldername Name of the folder were the message should be fetched from * @param msgnum Number of the message to fetch * @param mode there are three different modes: standard, reply and forward. reply and forward will enter the message * into the current work element of the user and set some additional flags on the message if the user * has enabled this option. * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_STANDARD * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_REPLY * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_FORWARD */ public void getMessage(String folderhash, int msgnum, int mode) throws NoSuchFolderException, WebMailException { // security reasons: // attachments=null; try { TimeZone tz = TimeZone.getDefault(); DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT, user.getPreferredLocale()); df.setTimeZone(tz); Folder folder = getFolder(folderhash); Element xml_folder = model.getFolder(folderhash); if (folder == null) { throw new NoSuchFolderException("No such folder: " + folderhash); } if (folder.isOpen() && folder.getMode() == Folder.READ_WRITE) { folder.close(false); folder.open(Folder.READ_ONLY); } else if (!folder.isOpen()) { folder.open(Folder.READ_ONLY); } MimeMessage m = (MimeMessage) folder.getMessage(msgnum); String messageid; try { StringTokenizer tok = new StringTokenizer(m.getMessageID(), "<>"); messageid = tok.nextToken(); } catch (NullPointerException ex) { // For mail servers that don't generate a Message-ID (Outlook et al) messageid = user.getLogin() + "." + msgnum + ".jwebmail@" + user.getDomain(); } Element xml_current = model.setCurrentMessage(messageid); XMLMessage xml_message = model.getMessage(xml_folder, m.getMessageNumber() + "", messageid); /* Check whether we already cached this message (not only headers but complete)*/ boolean cached = xml_message.messageCompletelyCached(); /* If we cached the message, we don't need to fetch it again */ if (!cached) { //Element xml_header=model.getHeader(xml_message); try { String from = MimeUtility.decodeText(Helper.joinAddress(m.getFrom())); String replyto = MimeUtility.decodeText(Helper.joinAddress(m.getReplyTo())); String to = MimeUtility .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.TO))); String cc = MimeUtility .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.CC))); String bcc = MimeUtility .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.BCC))); Date date_orig = m.getSentDate(); String date = getStringResource("no date"); if (date_orig != null) { date = df.format(date_orig); } String subject = ""; if (m.getSubject() != null) { subject = MimeUtility.decodeText(m.getSubject()); } if (subject == null || subject.equals("")) { subject = getStringResource("no subject"); } try { Flags.Flag[] sf = m.getFlags().getSystemFlags(); for (int j = 0; j < sf.length; j++) { if (sf[j] == Flags.Flag.RECENT) xml_message.setAttribute("recent", "true"); if (sf[j] == Flags.Flag.SEEN) xml_message.setAttribute("seen", "true"); if (sf[j] == Flags.Flag.DELETED) xml_message.setAttribute("deleted", "true"); if (sf[j] == Flags.Flag.ANSWERED) xml_message.setAttribute("answered", "true"); if (sf[j] == Flags.Flag.DRAFT) xml_message.setAttribute("draft", "true"); if (sf[j] == Flags.Flag.FLAGGED) xml_message.setAttribute("flagged", "true"); if (sf[j] == Flags.Flag.USER) xml_message.setAttribute("user", "true"); } } catch (NullPointerException ex) { } if (m.getContentType().toUpperCase().startsWith("MULTIPART/")) { xml_message.setAttribute("attachment", "true"); } int size = m.getSize(); size /= 1024; xml_message.setAttribute("size", (size > 0 ? size + "" : "<1") + " kB"); /* Set all of what we found into the DOM */ xml_message.setHeader("FROM", from); xml_message.setHeader("SUBJECT", Fancyfier.apply(subject)); xml_message.setHeader("TO", to); xml_message.setHeader("CC", cc); xml_message.setHeader("BCC", bcc); xml_message.setHeader("REPLY-TO", replyto); xml_message.setHeader("DATE", date); /* Decode MIME contents recursively */ xml_message.removeAllParts(); parseMIMEContent(m, xml_message, messageid); } catch (UnsupportedEncodingException e) { log.warn("Unsupported Encoding in parseMIMEContent: " + e.getMessage()); } } /* Set seen flag (Maybe make that threaded to improve performance) */ if (user.wantsSetFlags()) { if (folder.isOpen() && folder.getMode() == Folder.READ_ONLY) { folder.close(false); folder.open(Folder.READ_WRITE); } else if (!folder.isOpen()) { folder.open(Folder.READ_WRITE); } folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.SEEN), true); folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.RECENT), false); if ((mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY) { folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.ANSWERED), true); } } folder.close(false); /* In this part we determine whether the message was requested so that it may be used for further editing (replying or forwarding). In this case we set the current "work" message to the message we just fetched and then modifiy it a little (quote, add a "Re" to the subject, etc). */ XMLMessage work = null; if ((mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY || (mode & GETMESSAGE_MODE_FORWARD) == GETMESSAGE_MODE_FORWARD) { log.debug("Setting work message!"); work = model.setWorkMessage(xml_message); String newmsgid = WebMailServer.generateMessageID(user.getUserName()); if (work != null && (mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY) { String from = work.getHeader("FROM"); work.setHeader("FROM", user.getDefaultEmail()); work.setHeader("TO", from); work.prepareReply(getStringResource("reply subject prefix"), getStringResource("reply subject postfix"), getStringResource("reply message prefix"), getStringResource("reply message postfix")); } else if (work != null && (mode & GETMESSAGE_MODE_FORWARD) == GETMESSAGE_MODE_FORWARD) { String from = work.getHeader("FROM"); work.setHeader("FROM", user.getDefaultEmail()); work.setHeader("TO", ""); work.setHeader("CC", ""); work.prepareForward(getStringResource("forward subject prefix"), getStringResource("forward subject postfix"), getStringResource("forward message prefix"), getStringResource("forward message postfix")); /* Copy all references to MIME parts to the new message id */ for (String key : getMimeParts(work.getAttribute("msgid"))) { StringTokenizer tok2 = new StringTokenizer(key, "/"); tok2.nextToken(); String newkey = tok2.nextToken(); mime_parts_decoded.put(newmsgid + "/" + newkey, mime_parts_decoded.get(key)); } } /* Clear the msgnr and msgid fields at last */ work.setAttribute("msgnr", "0"); work.setAttribute("msgid", newmsgid); prepareCompose(); } } catch (MessagingException ex) { log.error("Failed to get message. Doing nothing instead.", ex); } }
From source file:org.apache.axis2.transport.mail.EMailSender.java
public void send() throws AxisFault { try {// ww w . j a v a 2 s.co m Session session = Session.getInstance(properties, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return passwordAuthentication; } }); MimeMessage msg = new MimeMessage(session); // Set date - required by rfc2822 msg.setSentDate(new java.util.Date()); // Set from - required by rfc2822 String from = properties.getProperty("mail.smtp.from"); if (from != null) { msg.setFrom(new InternetAddress(from)); } EndpointReference epr = null; MailToInfo mailToInfo; if (messageContext.getTo() != null && !messageContext.getTo().hasAnonymousAddress()) { epr = messageContext.getTo(); } if (epr != null) { if (!epr.hasNoneAddress()) { mailToInfo = new MailToInfo(epr); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToInfo.getEmailAddress())); } else { if (from != null) { mailToInfo = new MailToInfo(from); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToInfo.getEmailAddress())); } else { String error = EMailSender.class.getName() + "Couldn't countinue due to" + " FROM addressing is NULL"; log.error(error); throw new AxisFault(error); } } } else { // replyto : from : or reply-path; if (from != null) { mailToInfo = new MailToInfo(from); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToInfo.getEmailAddress())); } else { String error = EMailSender.class.getName() + "Couldn't countinue due to" + " FROM addressing is NULL and EPR is NULL"; log.error(error); throw new AxisFault(error); } } msg.setSubject("__ Axis2/Java Mail Message __"); if (mailToInfo.isxServicePath()) { msg.setHeader(Constants.X_SERVICE_PATH, "\"" + mailToInfo.getContentDescription() + "\""); } if (inReplyTo != null) { msg.setHeader(Constants.IN_REPLY_TO, inReplyTo); } createMailMimeMessage(msg, mailToInfo, format); Transport.send(msg); log.info("Message being send. [Action = ]" + messageContext.getOptions().getAction()); sendReceive(messageContext, msg.getMessageID()); } catch (AddressException e) { throw new AxisFault(e.getMessage(), e); } catch (MessagingException e) { throw new AxisFault(e.getMessage(), e); } }
From source file:org.apache.nifi.processors.email.ExtractEmailHeaders.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) { final ComponentLog logger = getLogger(); final List<FlowFile> invalidFlowFilesList = new ArrayList<>(); final List<FlowFile> processedFlowFilesList = new ArrayList<>(); final FlowFile originalFlowFile = session.get(); if (originalFlowFile == null) { return;/*from ww w. j a va2 s.c o m*/ } final List<String> capturedHeadersList = Arrays .asList(context.getProperty(CAPTURED_HEADERS).getValue().toLowerCase().split(":")); final Map<String, String> attributes = new HashMap<>(); session.read(originalFlowFile, new InputStreamCallback() { @Override public void process(final InputStream rawIn) throws IOException { try (final InputStream in = new BufferedInputStream(rawIn)) { Properties props = new Properties(); Session mailSession = Session.getDefaultInstance(props, null); MimeMessage originalMessage = new MimeMessage(mailSession, in); MimeMessageParser parser = new MimeMessageParser(originalMessage).parse(); // RFC-2822 determines that a message must have a "From:" header // if a message lacks the field, it is flagged as invalid Address[] from = originalMessage.getFrom(); Date sentDate = originalMessage.getSentDate(); if (from == null || sentDate == null) { // Throws MessageException due to lack of minimum required headers throw new MessagingException("Message failed RFC2822 validation"); } else if (capturedHeadersList.size() > 0) { Enumeration headers = originalMessage.getAllHeaders(); while (headers.hasMoreElements()) { Header header = (Header) headers.nextElement(); if (StringUtils.isNotEmpty(header.getValue()) && capturedHeadersList.contains(header.getName().toLowerCase())) { attributes.put("email.headers." + header.getName().toLowerCase(), header.getValue()); } } } if (Array.getLength(originalMessage.getAllRecipients()) > 0) { for (int toCount = 0; toCount < ArrayUtils .getLength(originalMessage.getRecipients(Message.RecipientType.TO)); toCount++) { attributes.put(EMAIL_HEADER_TO + "." + toCount, originalMessage.getRecipients(Message.RecipientType.TO)[toCount].toString()); } for (int toCount = 0; toCount < ArrayUtils .getLength(originalMessage.getRecipients(Message.RecipientType.BCC)); toCount++) { attributes.put(EMAIL_HEADER_BCC + "." + toCount, originalMessage.getRecipients(Message.RecipientType.BCC)[toCount].toString()); } for (int toCount = 0; toCount < ArrayUtils .getLength(originalMessage.getRecipients(Message.RecipientType.CC)); toCount++) { attributes.put(EMAIL_HEADER_CC + "." + toCount, originalMessage.getRecipients(Message.RecipientType.CC)[toCount].toString()); } } // Incredibly enough RFC-2822 specified From as a "mailbox-list" so an array I returned by getFrom for (int toCount = 0; toCount < ArrayUtils.getLength(originalMessage.getFrom()); toCount++) { attributes.put(EMAIL_HEADER_FROM + "." + toCount, originalMessage.getFrom()[toCount].toString()); } if (StringUtils.isNotEmpty(originalMessage.getMessageID())) { attributes.put(EMAIL_HEADER_MESSAGE_ID, originalMessage.getMessageID()); } if (originalMessage.getReceivedDate() != null) { attributes.put(EMAIL_HEADER_RECV_DATE, originalMessage.getReceivedDate().toString()); } if (originalMessage.getSentDate() != null) { attributes.put(EMAIL_HEADER_SENT_DATE, originalMessage.getSentDate().toString()); } if (StringUtils.isNotEmpty(originalMessage.getSubject())) { attributes.put(EMAIL_HEADER_SUBJECT, originalMessage.getSubject()); } // Zeroes EMAIL_ATTACHMENT_COUNT attributes.put(EMAIL_ATTACHMENT_COUNT, "0"); // But insert correct value if attachments are present if (parser.hasAttachments()) { attributes.put(EMAIL_ATTACHMENT_COUNT, String.valueOf(parser.getAttachmentList().size())); } } catch (Exception e) { // Message is invalid or triggered an error during parsing attributes.clear(); logger.error("Could not parse the flowfile {} as an email, treating as failure", new Object[] { originalFlowFile, e }); invalidFlowFilesList.add(originalFlowFile); } } }); if (attributes.size() > 0) { FlowFile updatedFlowFile = session.putAllAttributes(originalFlowFile, attributes); logger.info("Extracted {} headers into {} file", new Object[] { attributes.size(), updatedFlowFile }); processedFlowFilesList.add(updatedFlowFile); } session.transfer(processedFlowFilesList, REL_SUCCESS); session.transfer(invalidFlowFilesList, REL_FAILURE); }
From source file:davmail.exchange.ExchangeSession.java
/** * Send message in reader to recipients. * Detect visible recipients in message body to determine bcc recipients * * @param rcptToRecipients recipients list * @param mimeMessage mime message/*w ww.j a v a 2 s .co m*/ * @throws IOException on error * @throws MessagingException on error */ public void sendMessage(List<String> rcptToRecipients, MimeMessage mimeMessage) throws IOException, MessagingException { // detect duplicate send command String messageId = mimeMessage.getMessageID(); if (lastSentMessageId != null && lastSentMessageId.equals(messageId)) { LOGGER.debug("Dropping message id " + messageId + ": already sent"); return; } lastSentMessageId = messageId; convertResentHeader(mimeMessage, "From"); convertResentHeader(mimeMessage, "To"); convertResentHeader(mimeMessage, "Cc"); convertResentHeader(mimeMessage, "Bcc"); convertResentHeader(mimeMessage, "Message-Id"); mimeMessage.removeHeader("From"); // remove visible recipients from list Set<String> visibleRecipients = new HashSet<String>(); List<InternetAddress> recipients = getAllRecipients(mimeMessage); for (InternetAddress address : recipients) { visibleRecipients.add((address.getAddress().toLowerCase())); } for (String recipient : rcptToRecipients) { if (!visibleRecipients.contains(recipient.toLowerCase())) { mimeMessage.addRecipient(javax.mail.Message.RecipientType.BCC, new InternetAddress(recipient)); } } sendMessage(mimeMessage); }
From source file:com.riq.MailHandlerServlet.java
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { log.info("Inside MailServlet doPost"); // TODO get path information to determine target Department for this email PersistenceManager pm = PMF.get().getPersistenceManager(); Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); try {//from w w w . j av a 2 s . c o m MimeMessage msg = new MimeMessage(session, req.getInputStream()); Address sender = msg.getFrom()[0]; Address replyTo = msg.getReplyTo()[0]; // DEBUG // log.info("Message Class: " + msg.getClass()); // log.info("Message Stream: " + msg.getInputStream()); // log.info("Message RawStream: " + msg.getRawInputStream()); // log.info("Message Flags: " + msg.getFlags()); // log.info("Message Content: " + msg.getContent().toString()); // log.info("Message ContentID: " + msg.getContentID()); // log.info("Message ContentMD: " + msg.getContentMD5()); // log.info("Message ContentType: " + msg.getContentType()); // log.info("Message Description: " + msg.getDescription()); // log.info("Message Disposition: " + msg.getDisposition()); // log.info("Message Encoding: " + msg.getEncoding()); // log.info("Message Filename: " + msg.getFileName()); // log.info("Message Line Count: " + msg.getLineCount()); // log.info("Message ID: " + msg.getMessageID()); // log.info("Message Number: " + msg.getMessageNumber()); // log.info("Message Size: " + msg.getSize()); // log.info("Message Subject: " + msg.getSubject()); // log.info("Message RawInputStream: " + msg.getRawInputStream().toString()); // log.info("Message ReplyTo: " + replyTo); // log.info("Message Sender: " + sender.toString()); // log.info("Request URL TO: " + getServletContext()); String alertMsgString = getText(msg); alertMsgString = alertMsgString.replaceAll("Begin forwarded message:", ""); alertMsgString = alertMsgString.replaceAll("Forwarded message", ""); alertMsgString = alertMsgString.replaceAll("Dispatch@co.morris.nj.us", ""); alertMsgString = alertMsgString.replaceAll("Date:", ""); alertMsgString = alertMsgString.replaceAll(">", ""); alertMsgString = alertMsgString.replaceAll("::", "-"); alertMsgString = alertMsgString.replaceAll("< ", ""); alertMsgString = alertMsgString.replaceAll("----------", ""); alertMsgString = alertMsgString.replaceAll("Subject:", ""); alertMsgString = alertMsgString.replaceAll("To:", ""); alertMsgString = alertMsgString.replaceAll("From:", ""); // Added to grab gmail confirmations // alertMsgString = alertMsgString.substring(50, 300); try { String queryDept = "select from " + Department.class.getName() + // TODO: johnreilly workaround for getting allRecipients... // " where dispatchId == '" + toAddressDigitsOnly + "' " + " where dispatchId == '2599' " + " && fromEmail == '" + sender + "' "; log.info("queryDept: " + queryDept); List<Department> depts = (List<Department>) pm.newQuery(queryDept).execute(); if (depts.size() != 0) { for (Department d : depts) { // need to filter further e.g. last two hours String queryAlert = "select from " + Alert.class.getName() + " where deptId == " + depts.get(0).getid() + " && messageId == '" + msg.getMessageID() + "' "; log.info("queryAlert: " + queryAlert); List<Alert> alerts = (List<Alert>) pm.newQuery(queryAlert).execute(); log.info("queryAlert Result Qty: " + alerts.size()); if (alerts.size() == 0) { riqGeocode(alertMsgString); // geocode the address from the Alert Map<String, String> geoResults = riqGeocode(alertMsgString); log.info("lat print: " + geoResults.get("lat")); log.info("lng print: " + geoResults.get("lng")); // create the alert Long deptId = depts.get(0).getid(); Long timeStamp = System.currentTimeMillis(); Alert a = new Alert(deptId, timeStamp, alertMsgString.trim(), sender.toString(), "Active", "", geoResults.get("lat"), geoResults.get("lng"), msg.getMessageID()); pm.makePersistent(a); // query to get id of this alert String queryThisAlert = "select from " + Alert.class.getName() + " where deptId == " + deptId + " " + " && timeStamp == " + timeStamp; log.info("queryThisAlert: " + queryThisAlert); List<Alert> thisAlert = (List<Alert>) pm.newQuery(queryThisAlert).execute(); log.info("queryCurrentAlert Result Qty: " + thisAlert.size()); // create Tracking records for "special" Locations String querySpecialLocs = "select from " + Location.class.getName() + " where special == 'yes' && deptId == " + deptId; log.info("querySpecialLocs: " + querySpecialLocs); List<Location> specialLocs = (List<Location>) pm.newQuery(querySpecialLocs).execute(); log.info("querySpecialLocs qty: " + specialLocs.size()); for (Location specL : specialLocs) { Tracking tSL = new Tracking(deptId, thisAlert.get(0).getid(), specL.getid(), System.currentTimeMillis(), null, // TODO: johnreilly authorId tbd "location", specL.getid(), null, "autoAddLocation"); pm.makePersistent(tSL); } // search Dept for Location where distant Members presumed not to be responding are set String queryFarawayLocs = "select from " + Location.class.getName() + " where vru == '2' && deptId == " + deptId; log.info("querySpecialLocs: " + queryFarawayLocs); List<Location> farawayLoc = (List<Location>) pm.newQuery(queryFarawayLocs).execute(); log.info("queryFarawayLocs qty: " + farawayLoc.size()); // create Tracking records for Members presumed not to be responder due to fresh ETA String queryFarAwayResponders = "select from " + Member.class.getName() + " where distGroup == '4' "; log.info("queryFarAwayResponders: " + queryFarAwayResponders); List<Member> farawayMembers = (List<Member>) pm.newQuery(queryFarAwayResponders) .execute(); log.info("queryFarAwayResponders qty: " + farawayMembers.size()); if (farawayMembers.size() != 0) { for (Member far : farawayMembers) { Tracking tMFAR = new Tracking(deptId, thisAlert.get(0).getid(), farawayLoc.get(0).getid(), System.currentTimeMillis(), null, // TODO: johnreilly authorId tbd "farawayAddMember", far.getid(), null, responseType); pm.makePersistent(tMFAR); } } // TODO: testing restriction HACKER - remove at launch // send alert email String queryMember = "select from " + Member.class.getName() + " where deptId == " + deptId + " && type == 'Hacker' "; List<Member> members = (List<Member>) pm.newQuery(queryMember).execute(); //TODO Geocode address to insure easy navigation //TODO johnreilly: add street and town fields to Alert msg.setFrom( new InternetAddress("admin@responderiq05.appspotmail.com", "FirstResponder")); msg.setSubject("Alert!"); msg.setText(" Y=" + d.getinboundVRU1() + "&N=" + d.getinboundVRU2() + // "&3=" + d.getinboundVRU3() + "&A=" + thisAlert.get(0).getalertMsgString()); // send message to all dept members who permit tracking (and sending email alerts) for (Member m : members) { msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m.getsmsAddress(), m.getfirstName() + "" + m.getlastName())); log.info("Member: " + m.getsmsAddress() + "|" + m.getlastName()); } } // only process for one department - should only be one department break; } } } catch (MessagingException me) { log.info("Error: Messaging"); } catch (IndexOutOfBoundsException mi) { log.info("Error: Out of Bounds"); } // Do not send alert notification if email is a Google Confirmation // if (! sender.toString().contains("mail-noreply@google.com")) { // Transport.send(msg); // } } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { pm.close(); } }
From source file:com.zimbra.cs.service.mail.ToXML.java
/** Encodes an Invite stored within a calendar item object into <m> element * with <mp> elements./*from www. ja va 2s .c om*/ * @param parent The Element to add the new <tt><m></tt> to. * @param ifmt The SOAP request's context. * @param calItem The calendar item to serialize. * @param iid The requested item; the contained subpart will be used to * pick the Invite out of the calendar item's blob & metadata. * @param part If non-null, we'll serialuize this message/rfc822 subpart * of the specified Message instead of the Message itself. * @param maxSize The maximum amount of content to inline (<=0 is unlimited). * @param wantHTML <tt>true</tt> to prefer HTML parts as the "body", * <tt>false</tt> to prefer text/plain parts. * @param neuter Whether to rename "src" attributes on HTML <img> tags. * @param headers Extra message headers to include in the returned element. * @param serializeType If <tt>false</tt>, always serializes as an * <tt><m></tt> element. * @return The newly-created <tt><m></tt> Element, which has already * been added as a child to the passed-in <tt>parent</tt>. * @throws ServiceException */ public static Element encodeInviteAsMP(Element parent, ItemIdFormatter ifmt, OperationContext octxt, CalendarItem calItem, String recurIdZ, ItemId iid, String part, int maxSize, boolean wantHTML, boolean neuter, Set<String> headers, boolean serializeType, boolean wantExpandGroupInfo) throws ServiceException { int invId = iid.getSubpartId(); Invite[] invites = calItem.getInvites(invId); boolean isPublic = calItem.isPublic(); boolean showAll = isPublic || allowPrivateAccess(octxt, calItem); boolean wholeMessage = (part == null || part.trim().isEmpty()); Element m; if (wholeMessage) { // We want to return the MODIFIED_CONFLICT fields to enable conflict detection on modify. int fields = NOTIFY_FIELDS | Change.CONFLICT; m = encodeMessageCommon(parent, ifmt, octxt, calItem, fields, serializeType); m.addAttribute(MailConstants.A_ID, ifmt.formatItemId(calItem, invId)); } else { m = parent.addElement(MailConstants.E_MSG); m.addAttribute(MailConstants.A_ID, ifmt.formatItemId(calItem, invId)); m.addAttribute(MailConstants.A_PART, part); } try { MimeMessage mm = calItem.getSubpartMessage(invId); if (mm != null) { if (!wholeMessage) { MimePart mp = Mime.getMimePart(mm, part); if (mp == null) { throw MailServiceException.NO_SUCH_PART(part); } Object content = Mime.getMessageContent(mp); if (!(content instanceof MimeMessage)) { throw MailServiceException.NO_SUCH_PART(part); } mm = (MimeMessage) content; } else { part = ""; } if (showAll) { addEmails(m, Mime.parseAddressHeader(mm, "From"), EmailType.FROM); addEmails(m, Mime.parseAddressHeader(mm, "Sender"), EmailType.SENDER); addEmails(m, Mime.parseAddressHeader(mm, "Reply-To"), EmailType.REPLY_TO); addEmails(m, Mime.parseAddressHeader(mm, "To"), EmailType.TO); addEmails(m, Mime.parseAddressHeader(mm, "Cc"), EmailType.CC); addEmails(m, Mime.parseAddressHeader(mm, "Bcc"), EmailType.BCC); String subject = Mime.getSubject(mm); if (subject != null) { m.addAttribute(MailConstants.E_SUBJECT, StringUtil.stripControlCharacters(subject), Element.Disposition.CONTENT); } String messageID = mm.getMessageID(); if (messageID != null && !messageID.trim().isEmpty()) { m.addAttribute(MailConstants.E_MSG_ID_HDR, StringUtil.stripControlCharacters(messageID), Element.Disposition.CONTENT); } if (!wholeMessage) { m.addAttribute(MailConstants.A_SIZE, mm.getSize()); } java.util.Date sent = mm.getSentDate(); if (sent != null) { m.addAttribute(MailConstants.A_SENT_DATE, sent.getTime()); } } } Element invElt = m.addElement(MailConstants.E_INVITE); setCalendarItemType(invElt, calItem.getType()); encodeTimeZoneMap(invElt, calItem.getTimeZoneMap()); if (invites.length > 0) { if (showAll) { encodeCalendarReplies(invElt, calItem, invites[0], recurIdZ); } for (Invite inv : invites) { encodeInviteComponent(invElt, ifmt, octxt, calItem, (ItemId) null, inv, NOTIFY_FIELDS, neuter); } } //encodeAlarmTimes(invElt, calItem); if (mm != null && showAll) { if (headers != null) { for (String name : headers) { String[] values = mm.getHeader(name); if (values == null) { continue; } for (int i = 0; i < values.length; i++) { m.addKeyValuePair(name, values[i], MailConstants.A_HEADER, MailConstants.A_ATTRIBUTE_NAME); } } } List<MPartInfo> parts = Mime.getParts(mm, getDefaultCharset(calItem)); if (parts != null && !parts.isEmpty()) { Set<MPartInfo> bodies = Mime.getBody(parts, wantHTML); addParts(m, parts.get(0), bodies, part, maxSize, neuter, true, getDefaultCharset(calItem), true); } } if (wantExpandGroupInfo) { Account authedAcct = octxt.getAuthenticatedUser(); Account requestedAcct = calItem.getMailbox().getAccount(); encodeAddrsWithGroupInfo(m, requestedAcct, authedAcct); } } catch (IOException ex) { throw ServiceException.FAILURE(ex.getMessage(), ex); } catch (MessagingException ex) { throw ServiceException.FAILURE(ex.getMessage(), ex); } return m; }
From source file:edu.stanford.muse.email.EmailFetcherStats.java
/** * Key method for importing email: converts a javamail obj. to our own data structure (EmailDocument) *//* w ww .j a v a 2s . c o m*/ //public EmailDocument convertToEmailDocument(MimeMessage m, int num, String url) throws MessagingException, IOException private EmailDocument convertToEmailDocument(MimeMessage m, String id) throws MessagingException, IOException { // get the date. // prevDate is a hack for the cases where the message is lacking an explicit Date: header. e.g. // From hangal Sun Jun 10 13:46:46 2001 // To: ewatkins@stanford.edu // Subject: Re: return value bugs // though the date is on the From separator line, the mbox provider fails to parse it and provide it to us. // so as a hack, we will assign such messages the same date as the previous one this fetcher has seen! ;-) // update: having the exact same date causes the message to be considered a duplicate, so just increment // the timestamp it by 1 millisecond! // a better fix would be to improve the parsing in the provider boolean hackyDate = false; Date d = m.getSentDate(); if (d == null) d = m.getReceivedDate(); if (d == null) { if (prevDate != null) { long newTime = prevDate.getTime() + 1L; // added +1 so that this email is not considered the same object as the prev. one if they are in the same thread d = new Date(newTime); dataErrors.add("No date for message id:" + id + ": " + EmailUtils.formatMessageHeader(m) + " assigned approximate date"); } else { d = INVALID_DATE; // wrong, but what can we do... :-( dataErrors.add("No date for message id:" + id + ": " + EmailUtils.formatMessageHeader(m) + " assigned deliberately invalid date"); } hackyDate = true; } else { Calendar c = new GregorianCalendar(); c.setTime(d); int yy = c.get(Calendar.YEAR); if (yy < 1960 || yy > 2020) { dataErrors.add("Probably bad date: " + Util.formatDate(c) + " message: " + EmailUtils.formatMessageHeader(m)); hackyDate = true; } } if (hackyDate && prevDate != null) { long newTime = prevDate.getTime() + 1L; // added +1 so that this email is not considered the same object as the prev. one if they are in the same thread d = new Date(newTime); Util.ASSERT(!d.equals(prevDate)); } Calendar c = new GregorianCalendar(); c.setTime(d != null ? d : new Date()); prevDate = d; Address to[] = null, cc[] = null, bcc[] = null; Address[] from = null; try { // allrecip = m.getAllRecipients(); // turns out to be too expensive because it looks for newsgroup headers for imap // assemble to, cc, bcc into a list and copy it into allrecip List<Address> list = new ArrayList<Address>(); from = m.getFrom(); to = m.getRecipients(Message.RecipientType.TO); if (to != null) list.addAll(Arrays.asList(to)); cc = m.getRecipients(Message.RecipientType.CC); if (cc != null) list.addAll(Arrays.asList(cc)); bcc = m.getRecipients(Message.RecipientType.BCC); if (bcc != null) list.addAll(Arrays.asList(bcc)); // intern the strings in these addresses to save memory cos they are repeated often in a large archive internAddressList(from); internAddressList(to); internAddressList(cc); internAddressList(bcc); } catch (AddressException ae) { String s = "Bad address in folder " + folder_name() + " message id" + id + " " + ae; dataErrors.add(s); } // take a deep breath. This object is going to live longer than most of us. EmailDocument ed = new EmailDocument(id, email_source(), folder_name(), to, cc, bcc, from, m.getSubject(), m.getMessageID(), c.getTime()); String[] headers = m.getHeader("List-Post"); if (headers != null && headers.length > 0) { // trim the headers because they usually look like: "<mailto:prpl-devel@lists.stanford.edu>" ed.sentToMailingLists = new String[headers.length]; int i = 0; for (String header : headers) { header = header.trim(); header = header.toLowerCase(); if (header.startsWith("<") && header.endsWith(">")) header = header.substring(1, header.length() - 1); if (header.startsWith("mailto:") && !"mailto:".equals(header)) // defensive check in case header == "mailto:" header = header.substring(("mailto:").length()); ed.sentToMailingLists[i++] = header; } } if (hackyDate) { String s = "Guessed date " + Util.formatDate(c) + " for message id: " + id + ": " + ed.getHeader(); dataErrors.add(s); ed.hackyDate = true; } // check if the message has attachments. // if it does and we're not downloading attachments, then we mark the ed as such. // otherwise we had a problem where a message header (and maybe text) was downloaded but without attachments in one run // but in a subsequent run where attachments were needed, we thought the message was already cached and there was no // need to recompute it, leaving the attachments field in this ed incorrect. List<String> attachmentNames = getAttachmentNames(m, m); if (!Util.nullOrEmpty(attachmentNames)) { ed.attachmentsYetToBeDownloaded = true; // will set it to false later if attachments really were downloaded (not sure why) // log.info ("added " + attachmentNames.size() + " attachments to message: " + ed); } return ed; }
From source file:com.zimbra.cs.service.mail.ToXML.java
/** Encodes a Message object into <m> element with <mp> elements for * message body.//from w ww. j a va 2 s .c o m * @param parent The Element to add the new <tt><m></tt> to. * @param ifmt The formatter to sue when serializing item ids. * @param msg The Message to serialize. * @param part If non-null, serialize this message/rfc822 subpart of * the Message instead of the Message itself. * @param maxSize TODO * @param wantHTML <tt>true</tt> to prefer HTML parts as the "body", * <tt>false</tt> to prefer text/plain parts. * @param neuter Whether to rename "src" attributes on HTML <img> tags. * @param headers Extra message headers to include in the returned element. * @param serializeType If <tt>false</tt>, always serializes as an * <tt><m></tt> element. * @param bestEffort If <tt>true</tt>, errors serializing part content * are swallowed. * @return The newly-created <tt><m></tt> Element, which has already * been added as a child to the passed-in <tt>parent</tt>. * @throws ServiceException */ private static Element encodeMessageAsMP(Element parent, ItemIdFormatter ifmt, OperationContext octxt, Message msg, String part, int maxSize, boolean wantHTML, boolean neuter, Set<String> headers, boolean serializeType, boolean wantExpandGroupInfo, boolean bestEffort, boolean encodeMissingBlobs, MsgContent wantContent) throws ServiceException { Element m = null; boolean success = false; try { boolean wholeMessage = part == null || part.trim().isEmpty(); if (wholeMessage) { m = encodeMessageCommon(parent, ifmt, octxt, msg, NOTIFY_FIELDS, serializeType); m.addAttribute(MailConstants.A_ID, ifmt.formatItemId(msg)); } else { m = parent.addElement(MailConstants.E_MSG); m.addAttribute(MailConstants.A_ID, ifmt.formatItemId(msg)); m.addAttribute(MailConstants.A_PART, part); } MimeMessage mm = null; try { String requestedAccountId = octxt.getmRequestedAccountId(); String authtokenAccountId = octxt.getmAuthTokenAccountId(); boolean isDecryptionNotAllowed = StringUtils.isNotEmpty(authtokenAccountId) && !authtokenAccountId.equalsIgnoreCase(requestedAccountId); if (isDecryptionNotAllowed && Mime.isEncrypted(msg.getMimeMessage(false).getContentType())) { mm = msg.getMimeMessage(false); } else { mm = msg.getMimeMessage(); } } catch (MailServiceException e) { if (encodeMissingBlobs && MailServiceException.NO_SUCH_BLOB.equals(e.getCode())) { ZimbraLog.mailbox.error("Unable to get blob while encoding message", e); encodeEmail(m, msg.getSender(), EmailType.FROM); encodeEmail(m, msg.getSender(), EmailType.SENDER); if (msg.getRecipients() != null) { addEmails(m, Mime.parseAddressHeader(msg.getRecipients()), EmailType.TO); } m.addAttribute(MailConstants.A_SUBJECT, msg.getSubject()); Element mimePart = m.addElement(MailConstants.E_MIMEPART); mimePart.addAttribute(MailConstants.A_PART, 1); mimePart.addAttribute(MailConstants.A_BODY, true); mimePart.addAttribute(MailConstants.A_CONTENT_TYPE, MimeConstants.CT_TEXT_PLAIN); String errMsg = L10nUtil.getMessage(L10nUtil.MsgKey.errMissingBlob, msg.getAccount().getLocale(), ifmt.formatItemId(msg)); m.addAttribute(MailConstants.E_FRAG, errMsg, Element.Disposition.CONTENT); mimePart.addAttribute(MailConstants.E_CONTENT, errMsg, Element.Disposition.CONTENT); success = true; //not really success, but mark as such so the element is appended correctly return m; } throw e; } if (!wholeMessage) { MimePart mp = Mime.getMimePart(mm, part); if (mp == null) { throw MailServiceException.NO_SUCH_PART(part); } Object content = Mime.getMessageContent(mp); if (!(content instanceof MimeMessage)) { throw MailServiceException.NO_SUCH_PART(part); } mm = (MimeMessage) content; } else { part = ""; } // Add fragment before emails to maintain consistent ordering // of elements with encodeConversation - need to do this to // overcome JAXB issues. String fragment = msg.getFragment(); if (fragment != null && !fragment.isEmpty()) { m.addAttribute(MailConstants.E_FRAG, fragment, Element.Disposition.CONTENT); } addEmails(m, Mime.parseAddressHeader(mm, "From"), EmailType.FROM); addEmails(m, Mime.parseAddressHeader(mm, "Sender"), EmailType.SENDER); addEmails(m, Mime.parseAddressHeader(mm, "Reply-To"), EmailType.REPLY_TO); addEmails(m, Mime.parseAddressHeader(mm, "To"), EmailType.TO); addEmails(m, Mime.parseAddressHeader(mm, "Cc"), EmailType.CC); addEmails(m, Mime.parseAddressHeader(mm, "Bcc"), EmailType.BCC); addEmails(m, Mime.parseAddressHeader(mm.getHeader("Resent-From", null), false), EmailType.RESENT_FROM); // read-receipts only get sent by the mailbox's owner if (!(octxt.isDelegatedRequest(msg.getMailbox()) && octxt.isOnBehalfOfRequest(msg.getMailbox()))) { addEmails(m, Mime.parseAddressHeader(mm, "Disposition-Notification-To"), EmailType.READ_RECEIPT); } String calIntendedFor = msg.getCalendarIntendedFor(); m.addAttribute(MailConstants.A_CAL_INTENDED_FOR, calIntendedFor); String subject = Mime.getSubject(mm); if (subject != null) { m.addAttribute(MailConstants.E_SUBJECT, StringUtil.stripControlCharacters(subject), Element.Disposition.CONTENT); } String messageID = mm.getMessageID(); if (messageID != null && !messageID.trim().isEmpty()) { m.addAttribute(MailConstants.E_MSG_ID_HDR, StringUtil.stripControlCharacters(messageID), Element.Disposition.CONTENT); } if (wholeMessage && msg.isDraft()) { if (!msg.getDraftOrigId().isEmpty()) { ItemId origId = new ItemId(msg.getDraftOrigId(), msg.getMailbox().getAccountId()); m.addAttribute(MailConstants.A_ORIG_ID, ifmt.formatItemId(origId)); } if (!msg.getDraftReplyType().isEmpty()) { m.addAttribute(MailConstants.A_REPLY_TYPE, msg.getDraftReplyType()); } if (!msg.getDraftIdentityId().isEmpty()) { m.addAttribute(MailConstants.A_IDENTITY_ID, msg.getDraftIdentityId()); } if (!msg.getDraftAccountId().isEmpty()) { m.addAttribute(MailConstants.A_FOR_ACCOUNT, msg.getDraftAccountId()); } String inReplyTo = mm.getHeader("In-Reply-To", null); if (inReplyTo != null && !inReplyTo.isEmpty()) { m.addAttribute(MailConstants.E_IN_REPLY_TO, StringUtil.stripControlCharacters(inReplyTo), Element.Disposition.CONTENT); } if (msg.getDraftAutoSendTime() != 0) { m.addAttribute(MailConstants.A_AUTO_SEND_TIME, msg.getDraftAutoSendTime()); } } if (!wholeMessage) { m.addAttribute(MailConstants.A_SIZE, mm.getSize()); } Date sent = mm.getSentDate(); if (sent != null) { m.addAttribute(MailConstants.A_SENT_DATE, sent.getTime()); } Calendar resent = DateUtil.parseRFC2822DateAsCalendar(mm.getHeader("Resent-Date", null)); if (resent != null) { m.addAttribute(MailConstants.A_RESENT_DATE, resent.getTimeInMillis()); } if (msg.isInvite() && msg.hasCalendarItemInfos()) { encodeInvitesForMessage(m, ifmt, octxt, msg, NOTIFY_FIELDS, neuter); } if (headers != null) { for (String name : headers) { String[] values = mm.getHeader(name); if (values != null) { for (int i = 0; i < values.length; i++) { m.addKeyValuePair(name, values[i], MailConstants.A_HEADER, MailConstants.A_ATTRIBUTE_NAME); } } } } List<MPartInfo> parts = Mime.getParts(mm, getDefaultCharset(msg)); if (parts != null && !parts.isEmpty()) { Set<MPartInfo> bodies = Mime.getBody(parts, wantHTML); addParts(m, parts.get(0), bodies, part, maxSize, neuter, false, getDefaultCharset(msg), bestEffort, wantContent); } if (wantExpandGroupInfo) { ZimbraLog.gal.trace("want expand group info"); Account authedAcct = octxt.getAuthenticatedUser(); Account requestedAcct = msg.getMailbox().getAccount(); encodeAddrsWithGroupInfo(m, requestedAcct, authedAcct); } else { ZimbraLog.gal.trace("do not want expand group info"); } success = true; // update crypto flags - isSigned/isEncrypted if (SmimeHandler.getHandler() != null) { if (!wholeMessage) { // check content type of attachment message for encryption flag SmimeHandler.getHandler().updateCryptoFlags(msg, m, mm, mm); } else { MimeMessage originalMimeMessage = msg.getMimeMessage(false); SmimeHandler.getHandler().updateCryptoFlags(msg, m, originalMimeMessage, mm); } } // if the mime it is signed if (Mime.isMultipartSigned(mm.getContentType()) || Mime.isPKCS7Signed(mm.getContentType())) { ZimbraLog.mailbox .debug("The message is signed. Forwarding it to SmimeHandler for signature verification."); if (SmimeHandler.getHandler() != null) { SmimeHandler.getHandler().verifyMessageSignature(msg.getMailbox().getAccount(), m, mm, octxt.getmResponseProtocol()); } } else { // if the original mime message was PKCS7-signed and it was // decoded and stored in cache as plain mime if ((mm instanceof Mime.FixedMimeMessage) && ((Mime.FixedMimeMessage) mm).isPKCS7Signed()) { if (SmimeHandler.getHandler() != null) { SmimeHandler.getHandler().addPKCS7SignedMessageSignatureDetails( msg.getMailbox().getAccount(), m, mm, octxt.getmResponseProtocol()); } } } return m; } catch (IOException ex) { throw ServiceException.FAILURE(ex.getMessage(), ex); } catch (MessagingException ex) { throw ServiceException.FAILURE(ex.getMessage(), ex); } finally { // don't leave turds around if we're going to retry if (!success && !bestEffort && m != null) { m.detach(); } } }
From source file:fr.gouv.culture.vitam.eml.EmlExtract.java
public static String extractInfoMessage(MimeMessage message, Element root, VitamArgument argument, ConfigLoader config) {/* www . j av a2s. c o m*/ File oldDir = argument.currentOutputDir; if (argument.currentOutputDir == null) { if (config.outputDir != null) { argument.currentOutputDir = new File(config.outputDir); } } Element keywords = XmlDom.factory.createElement(EMAIL_FIELDS.keywords.name); Element metadata = XmlDom.factory.createElement(EMAIL_FIELDS.metadata.name); String skey = ""; String id = config.addRankId(root); Address[] from = null; Element sub2 = null; try { from = message.getFrom(); } catch (MessagingException e1) { String[] partialResult; try { partialResult = message.getHeader("From"); if (partialResult != null && partialResult.length > 0) { sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.from.name); Element add = XmlDom.factory.createElement(EMAIL_FIELDS.fromUnit.name); add.setText(partialResult[0]); sub2.add(add); } } catch (MessagingException e) { } } Address sender = null; try { sender = message.getSender(); } catch (MessagingException e1) { String[] partialResult; try { partialResult = message.getHeader("Sender"); if (partialResult != null && partialResult.length > 0) { if (sub2 == null) { sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.from.name); Element add = XmlDom.factory.createElement(EMAIL_FIELDS.fromUnit.name); add.setText(partialResult[0]); sub2.add(add); } } } catch (MessagingException e) { } } if (from != null && from.length > 0) { String value0 = null; Element sub = (sub2 != null ? sub2 : XmlDom.factory.createElement(EMAIL_FIELDS.from.name)); if (sender != null) { value0 = addAddress(sub, EMAIL_FIELDS.fromUnit.name, sender, null); } for (Address address : from) { addAddress(sub, EMAIL_FIELDS.fromUnit.name, address, value0); } metadata.add(sub); } else if (sender != null) { Element sub = (sub2 != null ? sub2 : XmlDom.factory.createElement(EMAIL_FIELDS.from.name)); addAddress(sub, EMAIL_FIELDS.fromUnit.name, sender, null); metadata.add(sub); } else { if (sub2 != null) { metadata.add(sub2); } } Address[] replyTo = null; try { replyTo = message.getReplyTo(); if (replyTo != null && replyTo.length > 0) { Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.replyTo.name); for (Address address : replyTo) { addAddress(sub, EMAIL_FIELDS.fromUnit.name, address, null); } metadata.add(sub); } } catch (MessagingException e1) { String[] partialResult; try { partialResult = message.getHeader("ReplyTo"); if (partialResult != null && partialResult.length > 0) { sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.replyTo.name); addAddress(sub2, EMAIL_FIELDS.fromUnit.name, partialResult, null); /*Element add = XmlDom.factory.createElement(EMAIL_FIELDS.fromUnit.name); add.setText(partialResult[0]); sub2.add(add);*/ metadata.add(sub2); } } catch (MessagingException e) { } } Address[] toRecipients = null; try { toRecipients = message.getRecipients(Message.RecipientType.TO); if (toRecipients != null && toRecipients.length > 0) { Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.toRecipients.name); for (Address address : toRecipients) { addAddress(sub, EMAIL_FIELDS.toUnit.name, address, null); } metadata.add(sub); } } catch (MessagingException e1) { String[] partialResult; try { partialResult = message.getHeader("To"); if (partialResult != null && partialResult.length > 0) { sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.toRecipients.name); addAddress(sub2, EMAIL_FIELDS.toUnit.name, partialResult, null); /*for (String string : partialResult) { Element add = XmlDom.factory.createElement(EMAIL_FIELDS.toUnit.name); add.setText(string); sub2.add(add); }*/ metadata.add(sub2); } } catch (MessagingException e) { } } Address[] ccRecipients; try { ccRecipients = message.getRecipients(Message.RecipientType.CC); if (ccRecipients != null && ccRecipients.length > 0) { Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.ccRecipients.name); for (Address address : ccRecipients) { addAddress(sub, EMAIL_FIELDS.ccUnit.name, address, null); } metadata.add(sub); } } catch (MessagingException e1) { String[] partialResult; try { partialResult = message.getHeader("Cc"); if (partialResult != null && partialResult.length > 0) { sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.ccRecipients.name); addAddress(sub2, EMAIL_FIELDS.ccUnit.name, partialResult, null); /*for (String string : partialResult) { Element add = XmlDom.factory.createElement(EMAIL_FIELDS.ccUnit.name); add.setText(string); sub2.add(add); }*/ metadata.add(sub2); } } catch (MessagingException e) { } } Address[] bccRecipients; try { bccRecipients = message.getRecipients(Message.RecipientType.BCC); if (bccRecipients != null && bccRecipients.length > 0) { Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.bccRecipients.name); for (Address address : bccRecipients) { addAddress(sub, EMAIL_FIELDS.bccUnit.name, address, null); } metadata.add(sub); } } catch (MessagingException e1) { String[] partialResult; try { partialResult = message.getHeader("Cc"); if (partialResult != null && partialResult.length > 0) { sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.bccRecipients.name); addAddress(sub2, EMAIL_FIELDS.bccUnit.name, partialResult, null); /*for (String string : partialResult) { Element add = XmlDom.factory.createElement(EMAIL_FIELDS.bccUnit.name); add.setText(string); sub2.add(add); }*/ metadata.add(sub2); } } catch (MessagingException e) { } } try { String subject = message.getSubject(); if (subject != null) { Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.subject.name); sub.setText(StringUtils.unescapeHTML(subject, true, false)); metadata.add(sub); } Date sentDate = message.getSentDate(); if (sentDate != null) { Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.sentDate.name); sub.setText(sentDate.toString()); metadata.add(sub); } Date receivedDate = message.getReceivedDate(); if (receivedDate != null) { Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.receivedDate.name); sub.setText(receivedDate.toString()); metadata.add(sub); } String[] headers = message.getHeader("Received"); if (headers != null) { Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.receptionTrace.name); MailDateFormat mailDateFormat = null; long maxTime = 0; if (receivedDate == null) { mailDateFormat = new MailDateFormat(); } for (String string : headers) { Element sub3 = XmlDom.factory.createElement(EMAIL_FIELDS.trace.name); sub3.setText(StringUtils.unescapeHTML(string, true, false)); sub.add(sub3); if (receivedDate == null) { int pos = string.lastIndexOf(';'); if (pos > 0) { String recvdate = string.substring(pos + 2).replaceAll("\t\n\r\f", "").trim(); try { Date date = mailDateFormat.parse(recvdate); if (date.getTime() > maxTime) { maxTime = date.getTime(); } } catch (ParseException e) { } } } } if (receivedDate == null) { Element subdate = XmlDom.factory.createElement(EMAIL_FIELDS.receivedDate.name); Date date = new Date(maxTime); subdate.setText(date.toString()); metadata.add(subdate); } metadata.add(sub); } int internalSize = message.getSize(); if (internalSize > 0) { Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.emailSize.name); sub.setText(Integer.toString(internalSize)); metadata.add(sub); } String encoding = message.getEncoding(); if (encoding != null) { Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.encoding.name); sub.setText(StringUtils.unescapeHTML(encoding, true, false)); metadata.add(sub); } String description = message.getDescription(); if (description != null) { Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.description.name); sub.setText(StringUtils.unescapeHTML(description, true, false)); metadata.add(sub); } String contentType = message.getContentType(); if (contentType != null) { Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.contentType.name); sub.setText(StringUtils.unescapeHTML(contentType, true, false)); metadata.add(sub); } headers = message.getHeader("Content-Transfer-Encoding"); if (headers != null) { Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.contentTransferEncoding.name); StringBuilder builder = new StringBuilder(); for (String string : headers) { builder.append(StringUtils.unescapeHTML(string, true, false)); builder.append(' '); } sub.setText(builder.toString()); metadata.add(sub); } String[] contentLanguage = message.getContentLanguage(); if (contentLanguage != null) { Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.contentLanguage.name); StringBuilder builder = new StringBuilder(); for (String string : contentLanguage) { builder.append(StringUtils.unescapeHTML(string, true, false)); builder.append(' '); } sub.setText(builder.toString()); metadata.add(sub); } String contentId = message.getContentID(); if (contentId != null) { Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.contentId.name); sub.setText(StringUtils.removeChevron(StringUtils.unescapeHTML(contentId, true, false))); metadata.add(sub); } String disposition = message.getDisposition(); if (disposition != null) { Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.disposition.name); sub.setText(StringUtils.removeChevron(StringUtils.unescapeHTML(disposition, true, false))); metadata.add(sub); } headers = message.getHeader("Keywords"); if (headers != null) { Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.msgKeywords.name); StringBuilder builder = new StringBuilder(); for (String string : headers) { builder.append(StringUtils.unescapeHTML(string, true, false)); builder.append(' '); } sub.setText(builder.toString()); metadata.add(sub); } String messageId = message.getMessageID(); if (messageId != null) { messageId = StringUtils.removeChevron(StringUtils.unescapeHTML(messageId, true, false)).trim(); if (messageId.length() > 1) { Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.messageId.name); sub.setText(messageId); metadata.add(sub); } } headers = message.getHeader("In-Reply-To"); String inreplyto = null; if (headers != null) { StringBuilder builder = new StringBuilder(); for (String string : headers) { builder.append(StringUtils.removeChevron(StringUtils.unescapeHTML(string, true, false))); builder.append(' '); } inreplyto = builder.toString().trim(); if (inreplyto.length() > 0) { Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.inReplyTo.name); sub.setText(inreplyto); if (messageId != null && messageId.length() > 1) { String old = filEmls.get(inreplyto); if (old == null) { old = messageId; } else { old += "," + messageId; } filEmls.put(inreplyto, old); } metadata.add(sub); } } headers = message.getHeader("References"); if (headers != null) { Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.references.name); StringBuilder builder = new StringBuilder(); for (String string : headers) { builder.append(StringUtils.removeChevron(StringUtils.unescapeHTML(string, true, false))); builder.append(' '); } String[] refs = builder.toString().trim().split(" "); for (String string : refs) { if (string.length() > 0) { Element ref = XmlDom.factory.createElement(EMAIL_FIELDS.reference.name); ref.setText(string); sub.add(ref); } } metadata.add(sub); } Element prop = XmlDom.factory.createElement(EMAIL_FIELDS.properties.name); headers = message.getHeader("X-Priority"); if (headers == null) { headers = message.getHeader("Priority"); if (headers != null && headers.length > 0) { prop.addAttribute(EMAIL_FIELDS.priority.name, headers[0]); } } else if (headers != null && headers.length > 0) { String imp = headers[0]; try { int Priority = Integer.parseInt(imp); switch (Priority) { case 5: imp = "LOWEST"; break; case 4: imp = "LOW"; break; case 3: imp = "NORMAL"; break; case 2: imp = "HIGH"; break; case 1: imp = "HIGHEST"; break; default: imp = "LEV" + Priority; } } catch (NumberFormatException e) { // ignore since imp will be used as returned } prop.addAttribute(EMAIL_FIELDS.priority.name, imp); } headers = message.getHeader("Sensitivity"); if (headers != null && headers.length > 0) { prop.addAttribute(EMAIL_FIELDS.sensitivity.name, headers[0]); } headers = message.getHeader("X-RDF"); if (headers != null && headers.length > 0) { System.err.println("Found X-RDF"); StringBuilder builder = new StringBuilder(); for (String string : headers) { builder.append(string); builder.append("\n"); } try { byte[] decoded = org.apache.commons.codec.binary.Base64.decodeBase64(builder.toString()); String rdf = new String(decoded); Document tempDocument = DocumentHelper.parseText(rdf); Element xrdf = prop.addElement("x-rdf"); xrdf.add(tempDocument.getRootElement()); } catch (Exception e) { System.err.println("Cannot decode X-RDF: " + e.getMessage()); } } try { File old = argument.currentOutputDir; if (config.extractFile) { File newOutDir = new File(argument.currentOutputDir, id); newOutDir.mkdirs(); argument.currentOutputDir = newOutDir; } if (argument.extractKeyword) { skey = handleMessage(message, metadata, prop, id, argument, config); // should have hasAttachment if (prop.hasContent()) { metadata.add(prop); } if (metadata.hasContent()) { root.add(metadata); } ExtractInfo.exportMetadata(keywords, skey, "", config, null); if (keywords.hasContent()) { root.add(keywords); } } else { handleMessage(message, metadata, prop, id, argument, config); // should have hasAttachment if (prop.hasContent()) { metadata.add(prop); } if (metadata.hasContent()) { root.add(metadata); } } argument.currentOutputDir = old; } catch (IOException e) { System.err.println(StaticValues.LBL.error_error.get() + e.toString()); } try { message.getInputStream().close(); } catch (IOException e) { System.err.println(StaticValues.LBL.error_error.get() + e.toString()); } root.addAttribute(EMAIL_FIELDS.status.name, "ok"); } catch (MessagingException e) { System.err.println(StaticValues.LBL.error_error.get() + e.toString()); e.printStackTrace(); String status = "Error during identification"; root.addAttribute(EMAIL_FIELDS.status.name, status); } catch (Exception e) { System.err.println(StaticValues.LBL.error_error.get() + e.toString()); e.printStackTrace(); String status = "Error during identification"; root.addAttribute(EMAIL_FIELDS.status.name, status); } argument.currentOutputDir = oldDir; return skey; }