List of usage examples for javax.mail.internet MimeMessage getSentDate
@Override public Date getSentDate() throws MessagingException
From source file:com.qwazr.library.email.EmlParser.java
@Override public void parseContent(final MultivaluedMap<String, String> parameters, final InputStream inputStream, final String extension, final String mimeType, final ParserResultBuilder resultBuilder) throws Exception { final Session session = Session.getDefaultInstance(JAVAMAIL_PROPS); resultBuilder.metas().set(MIME_TYPE, findMimeType(extension, mimeType, this::findMimeTypeUsingDefault)); final MimeMessage mimeMessage = new MimeMessage(session, inputStream); final MimeMessageParser mimeMessageParser = new MimeMessageParser(mimeMessage).parse(); ParserFieldsBuilder document = resultBuilder.newDocument(); final String from = mimeMessageParser.getFrom(); if (from != null) document.add(FROM, from);//from w w w . jav a 2s. c o m for (Address address : mimeMessageParser.getTo()) document.add(RECIPIENT_TO, address.toString()); for (Address address : mimeMessageParser.getCc()) document.add(RECIPIENT_CC, address.toString()); for (Address address : mimeMessageParser.getBcc()) document.add(RECIPIENT_BCC, address.toString()); document.add(SUBJECT, mimeMessageParser.getSubject()); document.add(HTML_CONTENT, mimeMessageParser.getHtmlContent()); document.add(PLAIN_CONTENT, mimeMessageParser.getPlainContent()); document.add(SENT_DATE, mimeMessage.getSentDate()); document.add(RECEIVED_DATE, mimeMessage.getReceivedDate()); for (DataSource dataSource : mimeMessageParser.getAttachmentList()) { document.add(ATTACHMENT_NAME, dataSource.getName()); document.add(ATTACHMENT_TYPE, dataSource.getContentType()); // TODO Extract content from attachmend // if (parserSelector != null) { // Parser attachParser = parserSelector.parseStream( // getSourceDocument(), dataSource.getName(), // dataSource.getContentType(), null, // dataSource.getInputStream(), null, null, null); // if (attachParser != null) { // List<ParserResultItem> parserResults = attachParser // .getParserResults(); // if (parserResults != null) // for (ParserResultItem parserResult : parserResults) // result.addField( // ParserFieldEnum.email_attachment_content, // parserResult); // } // } } if (StringUtils.isEmpty(mimeMessageParser.getHtmlContent())) document.add(LANG_DETECTION, languageDetection(document, PLAIN_CONTENT, 10000)); else document.add(LANG_DETECTION, languageDetection(document, HTML_CONTENT, 10000)); }
From source file:com.silverpeas.mailinglist.service.job.TestMessageCheckerWithStubs.java
@Test public void testCheckNewMessages() throws MessagingException, IOException { org.jvnet.mock_javamail.Mailbox.clearAll(); MessageChecker messageChecker = getMessageChecker(); messageChecker.removeListener("componentId"); messageChecker.removeListener("thesimpsons@silverpeas.com"); messageChecker.removeListener("theflanders@silverpeas.com"); StubMessageListener mockListener1 = new StubMessageListener("thesimpsons@silverpeas.com"); StubMessageListener mockListener2 = new StubMessageListener("theflanders@silverpeas.com"); messageChecker.addMessageListener(mockListener1); messageChecker.addMessageListener(mockListener2); MimeMessage mail = new MimeMessage(messageChecker.getMailSession()); InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com"); InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com"); mail.addFrom(new InternetAddress[] { bart }); mail.addRecipient(RecipientType.TO, theSimpsons); mail.setSubject("Plain text Email test with attachment"); MimeBodyPart attachment = new MimeBodyPart( TestMessageCheckerWithStubs.class.getResourceAsStream("lemonde.html")); attachment.setDisposition(Part.INLINE); attachment.setFileName("lemonde.html"); MimeBodyPart body = new MimeBodyPart(); body.setText(textEmailContent);/*from ww w. j a v a2 s. c om*/ Multipart multiPart = new MimeMultipart(); multiPart.addBodyPart(body); multiPart.addBodyPart(attachment); mail.setContent(multiPart); mail.setSentDate(new Date()); Date sentDate1 = new Date(mail.getSentDate().getTime()); Transport.send(mail); mail = new MimeMessage(messageChecker.getMailSession()); bart = new InternetAddress("bart.simpson@silverpeas.com"); theSimpsons = new InternetAddress("thesimpsons@silverpeas.com"); mail.addFrom(new InternetAddress[] { bart }); mail.addRecipient(RecipientType.TO, theSimpsons); mail.setSubject("Plain text Email test"); mail.setText(textEmailContent); mail.setSentDate(new Date()); Date sentDate2 = new Date(mail.getSentDate().getTime()); Transport.send(mail); //Unauthorized email mail = new MimeMessage(messageChecker.getMailSession()); bart = new InternetAddress("marge.simpson@silverpeas.com"); theSimpsons = new InternetAddress("thesimpsons@silverpeas.com"); mail.addFrom(new InternetAddress[] { bart }); mail.addRecipient(RecipientType.TO, theSimpsons); mail.setSubject("Plain text Email test"); mail.setText(textEmailContent); mail.setSentDate(new Date()); Transport.send(mail); assertThat(org.jvnet.mock_javamail.Mailbox.get("thesimpsons@silverpeas.com").size(), is(3)); messageChecker.checkNewMessages(new Date()); assertThat(mockListener2.getMessageEvent(), is(nullValue())); MessageEvent event = mockListener1.getMessageEvent(); assertThat(event, is(notNullValue())); assertThat(event.getMessages(), is(notNullValue())); assertThat(event.getMessages(), hasSize(2)); Message message = event.getMessages().get(0); assertThat(message.getSender(), is("bart.simpson@silverpeas.com")); assertThat(message.getTitle(), is("Plain text Email test with attachment")); assertThat(message.getBody(), is(textEmailContent)); assertThat(message.getSummary(), is(textEmailContent.substring(0, 200))); assertThat(message.getSentDate().getTime(), is(sentDate1.getTime())); assertThat(message.getAttachmentsSize(), greaterThan(0L)); assertThat(message.getAttachments(), hasSize(1)); String path = MessageFormat.format(theSimpsonsAttachmentPath, new Object[] { messageChecker.getMailProcessor().replaceSpecialChars(message.getMessageId()) }); Attachment attached = message.getAttachments().iterator().next(); assertThat(attached.getPath(), is(path)); assertThat(message.getComponentId(), is("thesimpsons@silverpeas.com")); message = event.getMessages().get(1); assertThat(message.getSender(), is("bart.simpson@silverpeas.com")); assertThat(message.getTitle(), is("Plain text Email test")); assertThat(message.getBody(), is(textEmailContent)); assertThat(message.getSummary(), is(textEmailContent.substring(0, 200))); assertThat(message.getAttachmentsSize(), is(0L)); assertThat(message.getAttachments(), hasSize(0)); assertThat(message.getComponentId(), is("thesimpsons@silverpeas.com")); assertThat(message.getSentDate().getTime(), is(sentDate2.getTime())); }
From source file:com.duroty.service.Mailet.java
/** * DOCUMENT ME!/* w w w . j a v a 2s . c o m*/ * * @param hfactory DOCUMENT ME! * @param username DOCUMENT ME! * @param mime DOCUMENT ME! */ private void parseContacts(Session hsession, Users user, MimeMessage mime, String box) { try { Address[] addresses = null; Date sentDate = null; Date receivedDate = null; if (box.equals("SENT")) { addresses = mime.getAllRecipients(); sentDate = mime.getSentDate(); if (sentDate == null) { sentDate = new Date(); } } else { addresses = mime.getFrom(); receivedDate = mime.getReceivedDate(); if (receivedDate == null) { receivedDate = new Date(); } } if ((addresses != null) && (addresses.length > 0)) { String name = null; String email = null; for (int i = 0; i < addresses.length; i++) { if (addresses[i] instanceof InternetAddress) { InternetAddress xinet = (InternetAddress) addresses[i]; name = xinet.getPersonal(); if ((name != null) && (name.length() > 49)) { name = name.substring(0, 49); } email = xinet.getAddress(); } else { email = addresses[i].toString(); } Criteria crit1 = hsession.createCriteria(Contact.class); crit1.add(Restrictions.eq("users", user)); crit1.add(Restrictions.eq("conEmail", email)); Contact contact = (Contact) crit1.uniqueResult(); if (contact != null) { if (receivedDate != null) { contact.setConReceivedDate(receivedDate); } if (sentDate != null) { contact.setConSentDate(sentDate); } int freq = contact.getConCount(); contact.setConCount(freq + 1); if (!StringUtils.isBlank(name)) { name = name.replaceAll(",", " "); name = name.replaceAll(";", " "); contact.setConName(name); } hsession.update(contact); } else { contact = new Contact(); contact.setConEmail(email); contact.setConName(name); contact.setConReceivedDate(receivedDate); contact.setConSentDate(sentDate); contact.setConCount(new Integer(1)); contact.setUsers(user); hsession.save(contact); } hsession.flush(); try { if ((contact.getConSentDate() != null) && (contact.getConReceivedDate() != null)) { Criteria crit2 = hsession.createCriteria(Identity.class); crit2.add(Restrictions.eq("ideEmail", email)); crit2.add(Restrictions.eq("ideActive", new Boolean(true))); List list = crit2.list(); if (list != null) { Iterator scroll = list.iterator(); while (scroll.hasNext()) { Identity identity = (Identity) scroll.next(); Users buddy = identity.getUsers(); if ((buddy != null) && (user.getUseIdint() != buddy.getUseIdint())) { Criteria auxCrit = hsession.createCriteria(BuddyList.class); auxCrit.add(Restrictions.eq("usersByBuliOwnerIdint", user)); auxCrit.add(Restrictions.eq("usersByBuliBuddyIdint", buddy)); BuddyList buddyList = (BuddyList) auxCrit.uniqueResult(); if (buddyList != null) { buddyList.setBuliActive(true); buddyList.setBuliLastDate(new Date()); hsession.update(buddyList); } else { buddyList = new BuddyList(); buddyList.setBuliActive(true); buddyList.setBuliLastDate(new Date()); buddyList.setUsersByBuliBuddyIdint(buddy); buddyList.setUsersByBuliOwnerIdint(user); hsession.save(buddyList); } } } } hsession.flush(); } } catch (Exception e) { } } } } catch (Exception e) { } finally { } }
From source file:com.jaeksoft.searchlib.parser.EmlParser.java
@Override protected void parseContent(StreamLimiter streamLimiter, LanguageEnum lang) throws IOException, SearchLibException { Session session = Session.getDefaultInstance(JAVAMAIL_PROPS); try {/*from w w w .j av a 2s.c o m*/ MimeMessage mimeMessage = new MimeMessage(session, streamLimiter.getNewInputStream()); MimeMessageParser mimeMessageParser = new MimeMessageParser(mimeMessage).parse(); ParserResultItem result = getNewParserResultItem(); String from = mimeMessageParser.getFrom(); if (from != null) result.addField(ParserFieldEnum.email_display_from, from.toString()); for (Address address : mimeMessageParser.getTo()) result.addField(ParserFieldEnum.email_display_to, address.toString()); for (Address address : mimeMessageParser.getCc()) result.addField(ParserFieldEnum.email_display_cc, address.toString()); for (Address address : mimeMessageParser.getBcc()) result.addField(ParserFieldEnum.email_display_bcc, address.toString()); result.addField(ParserFieldEnum.subject, mimeMessageParser.getSubject()); result.addField(ParserFieldEnum.htmlSource, mimeMessageParser.getHtmlContent()); result.addField(ParserFieldEnum.content, mimeMessageParser.getPlainContent()); result.addField(ParserFieldEnum.email_sent_date, mimeMessage.getSentDate()); result.addField(ParserFieldEnum.email_received_date, mimeMessage.getReceivedDate()); for (DataSource dataSource : mimeMessageParser.getAttachmentList()) { result.addField(ParserFieldEnum.email_attachment_name, dataSource.getName()); result.addField(ParserFieldEnum.email_attachment_type, dataSource.getContentType()); if (parserSelector == null) continue; Parser attachParser = parserSelector.parseStream(getSourceDocument(), dataSource.getName(), dataSource.getContentType(), null, dataSource.getInputStream(), null, null, null); if (attachParser == null) continue; List<ParserResultItem> parserResults = attachParser.getParserResults(); if (parserResults != null) for (ParserResultItem parserResult : parserResults) result.addField(ParserFieldEnum.email_attachment_content, parserResult); } if (StringUtils.isEmpty(mimeMessageParser.getHtmlContent())) result.langDetection(10000, ParserFieldEnum.content); else result.langDetection(10000, ParserFieldEnum.htmlSource); } catch (Exception e) { throw new IOException(e); } }
From source file:com.silverpeas.mailinglist.service.job.TestMessageChecker.java
@Test public void testProcessEmailTextWithAttachment() throws MessagingException, IOException { MessageListener mockListener1 = mock(MessageListener.class); when(mockListener1.getComponentId()).thenReturn("componentId"); when(mockListener1.checkSender("bart.simpson@silverpeas.com")).thenReturn(Boolean.TRUE); MessageListener mockListener2 = mock(MessageListener.class); messageChecker.addMessageListener(mockListener1); messageChecker.addMessageListener(mockListener2); Map<String, MessageListener> listenersByEmail = new HashMap<String, MessageListener>(2); listenersByEmail.put("thesimpsons@silverpeas.com", mockListener1); listenersByEmail.put("theflanders@silverpeas.com", mockListener2); MimeMessage mail = new MimeMessage(messageChecker.getMailSession()); InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com"); InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com"); mail.addFrom(new InternetAddress[] { bart }); mail.addRecipient(RecipientType.TO, theSimpsons); mail.setSubject("Plain text Email test with attachment"); MimeBodyPart attachment = new MimeBodyPart(TestMessageChecker.class.getResourceAsStream("lemonde.html")); attachment.setDisposition(Part.INLINE); attachment.setFileName("lemonde.html"); MimeBodyPart body = new MimeBodyPart(); body.setText(textEmailContent);//from w w w . ja v a2s . co m Multipart multiPart = new MimeMultipart(); multiPart.addBodyPart(body); multiPart.addBodyPart(attachment); mail.setContent(multiPart); mail.setSentDate(new Date()); Date sentDate = new Date(mail.getSentDate().getTime()); Transport.send(mail); Map<MessageListener, MessageEvent> events = new HashMap<MessageListener, MessageEvent>(); messageChecker.processEmail(mail, events, listenersByEmail); assertNotNull(events); assertEquals(1, events.size()); assertNull(events.get(mockListener2)); MessageEvent event = events.get(mockListener1); assertNotNull(event); assertNotNull(event.getMessages()); assertEquals(1, event.getMessages().size()); Message message = event.getMessages().get(0); assertEquals("bart.simpson@silverpeas.com", message.getSender()); assertEquals("Plain text Email test with attachment", message.getTitle()); assertEquals(textEmailContent, message.getBody()); assertEquals(textEmailContent.substring(0, 200), message.getSummary()); assertEquals(ATT_SIZE, message.getAttachmentsSize()); assertEquals(1, message.getAttachments().size()); String path = MessageFormat.format(attachmentPath, messageChecker.getMailProcessor().replaceSpecialChars(message.getMessageId())); Attachment attached = message.getAttachments().iterator().next(); assertEquals(path, attached.getPath()); assertEquals("lemonde.html", attached.getFileName()); assertEquals("componentId", message.getComponentId()); assertEquals(sentDate.getTime(), message.getSentDate().getTime()); assertEquals("text/plain", message.getContentType()); org.jvnet.mock_javamail.Mailbox.clearAll(); verify(mockListener1, atLeastOnce()).checkSender("bart.simpson@silverpeas.com"); verify(mockListener1, times(2)).getComponentId(); }
From source file:edu.hawaii.soest.hioos.storx.StorXDispatcher.java
/** * A method that executes the reading of data from the email account to the * RBNB server after all configuration of settings, connections to hosts, * and thread initiatizing occurs. This method contains the detailed code * for reading the data and interpreting the data files. */// w ww .j a va 2 s . c o m protected boolean execute() { logger.debug("StorXDispatcher.execute() called."); boolean failed = true; // indicates overall success of execute() boolean messageProcessed = false; // indicates per message success // declare the account properties that will be pulled from the // email.account.properties.xml file String accountName = ""; String server = ""; String username = ""; String password = ""; String protocol = ""; String dataMailbox = ""; String processedMailbox = ""; String prefetch = ""; // fetch data from each sensor in the account list List accountList = this.xmlConfiguration.getList("account.accountName"); for (Iterator aIterator = accountList.iterator(); aIterator.hasNext();) { int aIndex = accountList.indexOf(aIterator.next()); // populate the email connection variables from the xml properties // file accountName = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").accountName"); server = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").server"); username = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").username"); password = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").password"); protocol = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").protocol"); dataMailbox = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").dataMailbox"); processedMailbox = (String) this.xmlConfiguration .getProperty("account(" + aIndex + ").processedMailbox"); prefetch = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").prefetch"); logger.debug("\n\nACCOUNT DETAILS: \n" + "accountName : " + accountName + "\n" + "server : " + server + "\n" + "username : " + username + "\n" + "password : " + password + "\n" + "protocol : " + protocol + "\n" + "dataMailbox : " + dataMailbox + "\n" + "processedMailbox: " + processedMailbox + "\n" + "prefetch : " + prefetch + "\n"); // get a connection to the mail server Properties props = System.getProperties(); props.setProperty("mail.store.protocol", protocol); props.setProperty("mail.imaps.partialfetch", prefetch); try { // create the imaps mail session this.mailSession = Session.getDefaultInstance(props, null); this.mailStore = mailSession.getStore(protocol); } catch (NoSuchProviderException nspe) { try { // pause for 10 seconds logger.debug( "There was a problem connecting to the IMAP server. " + "Waiting 10 seconds to retry."); Thread.sleep(10000L); this.mailStore = mailSession.getStore(protocol); } catch (NoSuchProviderException nspe2) { logger.debug("There was an error connecting to the mail server. The " + "message was: " + nspe2.getMessage()); nspe2.printStackTrace(); failed = true; return !failed; } catch (InterruptedException ie) { logger.debug("The thread was interrupted: " + ie.getMessage()); failed = true; return !failed; } } try { this.mailStore.connect(server, username, password); // get folder references for the inbox and processed data box Folder inbox = mailStore.getFolder(dataMailbox); inbox.open(Folder.READ_WRITE); Folder processed = this.mailStore.getFolder(processedMailbox); processed.open(Folder.READ_WRITE); Message[] msgs; while (!inbox.isOpen()) { inbox.open(Folder.READ_WRITE); } msgs = inbox.getMessages(); List<Message> messages = new ArrayList<Message>(); Collections.addAll(messages, msgs); // sort the messages found in the inbox by date sent Collections.sort(messages, new Comparator<Message>() { public int compare(Message message1, Message message2) { int value = 0; try { value = message1.getSentDate().compareTo(message2.getSentDate()); } catch (MessagingException e) { e.printStackTrace(); } return value; } }); logger.debug("Number of messages: " + messages.size()); for (Message message : messages) { // Copy the message to ensure we have the full attachment MimeMessage mimeMessage = (MimeMessage) message; MimeMessage copiedMessage = new MimeMessage(mimeMessage); // determine the sensor serial number for this message String messageSubject = copiedMessage.getSubject(); Date sentDate = copiedMessage.getSentDate(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM"); // The subfolder of the processed mail folder (e.g. 2016-12); String destinationFolder = formatter.format(sentDate); logger.debug("Message date: " + sentDate + "\tNumber: " + copiedMessage.getMessageNumber()); String[] subjectParts = messageSubject.split("\\s"); String loggerSerialNumber = "SerialNumber"; if (subjectParts.length > 1) { loggerSerialNumber = subjectParts[2]; } // Do we have a data attachment? If not, there's no data to // process if (copiedMessage.isMimeType("multipart/mixed")) { logger.debug("Message size: " + copiedMessage.getSize()); MimeMessageParser parser = new MimeMessageParser(copiedMessage); try { parser.parse(); } catch (Exception e) { logger.error("Failed to parse the MIME message: " + e.getMessage()); continue; } ByteBuffer messageAttachment = ByteBuffer.allocate(256); // init only logger.debug("Has attachments: " + parser.hasAttachments()); for (DataSource dataSource : parser.getAttachmentList()) { if (StringUtils.isNotBlank(dataSource.getName())) { logger.debug( "Attachment: " + dataSource.getName() + ", " + dataSource.getContentType()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); IOUtils.copy(dataSource.getInputStream(), outputStream); messageAttachment = ByteBuffer.wrap(outputStream.toByteArray()); } } // We now have the attachment and serial number. Parse the attachment // for the data components, look up the storXSource based on the serial // number, and push the data to the DataTurbine // parse the binary attachment StorXParser storXParser = new StorXParser(messageAttachment); // iterate through the parsed framesMap and handle each // frame // based on its instrument type BasicHierarchicalMap framesMap = (BasicHierarchicalMap) storXParser.getFramesMap(); Collection frameCollection = framesMap.getAll("/frames/frame"); Iterator framesIterator = frameCollection.iterator(); while (framesIterator.hasNext()) { BasicHierarchicalMap frameMap = (BasicHierarchicalMap) framesIterator.next(); // logger.debug(frameMap.toXMLString(1000)); String frameType = (String) frameMap.get("type"); String sensorSerialNumber = (String) frameMap.get("serialNumber"); // handle each instrument type if (frameType.equals("HDR")) { logger.debug("This is a header frame. Skipping it."); } else if (frameType.equals("STX")) { try { // handle StorXSource StorXSource source = (StorXSource) sourceMap.get(sensorSerialNumber); // process the data using the StorXSource // driver messageProcessed = source.process(this.xmlConfiguration, frameMap); } catch (ClassCastException cce) { } } else if (frameType.equals("SBE")) { try { // handle CTDSource CTDSource source = (CTDSource) sourceMap.get(sensorSerialNumber); // process the data using the CTDSource // driver messageProcessed = source.process(this.xmlConfiguration, frameMap); } catch (ClassCastException cce) { } } else if (frameType.equals("NLB")) { try { // handle ISUSSource ISUSSource source = (ISUSSource) sourceMap.get(sensorSerialNumber); // process the data using the ISUSSource // driver messageProcessed = source.process(this.xmlConfiguration, frameMap); } catch (ClassCastException cce) { } } else if (frameType.equals("NDB")) { try { // handle ISUSSource ISUSSource source = (ISUSSource) sourceMap.get(sensorSerialNumber); // process the data using the ISUSSource // driver messageProcessed = source.process(this.xmlConfiguration, frameMap); } catch (ClassCastException cce) { } } else { logger.debug("The frame type " + frameType + " is not recognized. Skipping it."); } } // end while() if (this.sourceMap.get(loggerSerialNumber) != null) { // Note: Use message (not copiedMessage) when setting flags if (!messageProcessed) { logger.info("Failed to process message: " + "Message Number: " + message.getMessageNumber() + " " + "Logger Serial:" + loggerSerialNumber); // leave it in the inbox, flagged as seen (read) message.setFlag(Flags.Flag.SEEN, true); logger.debug("Saw message " + message.getMessageNumber()); } else { // message processed successfully. Create a by-month sub folder if it doesn't exist // Copy the message and flag it deleted Folder destination = processed.getFolder(destinationFolder); boolean created = destination.create(Folder.HOLDS_MESSAGES); inbox.copyMessages(new Message[] { message }, destination); message.setFlag(Flags.Flag.DELETED, true); logger.debug("Deleted message " + message.getMessageNumber()); } // end if() } else { logger.debug("There is no configuration information for " + "the logger serial number " + loggerSerialNumber + ". Please add the configuration to the " + "email.account.properties.xml configuration file."); } // end if() } else { logger.debug("This is not a data email since there is no " + "attachment. Skipping it. Subject: " + messageSubject); } // end if() } // end for() // expunge messages and close the mail server store once we're // done inbox.expunge(); this.mailStore.close(); } catch (MessagingException me) { try { this.mailStore.close(); } catch (MessagingException me2) { failed = true; return !failed; } logger.info( "There was an error reading the mail message. The " + "message was: " + me.getMessage()); me.printStackTrace(); failed = true; return !failed; } catch (IOException me) { try { this.mailStore.close(); } catch (MessagingException me3) { failed = true; return !failed; } logger.info("There was an I/O error reading the message part. The " + "message was: " + me.getMessage()); me.printStackTrace(); failed = true; return !failed; } catch (IllegalStateException ese) { try { this.mailStore.close(); } catch (MessagingException me4) { failed = true; return !failed; } logger.info("There was an error reading messages from the folder. The " + "message was: " + ese.getMessage()); failed = true; return !failed; } finally { try { this.mailStore.close(); } catch (MessagingException me2) { logger.debug("Couldn't close the mail store: " + me2.getMessage()); } } } return !failed; }
From source file:edu.stanford.muse.email.EmailFetcherStats.java
/** * Key method for importing email: converts a javamail obj. to our own data structure (EmailDocument) *///from w ww . j a v a2 s.co 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:mitm.common.pdf.MessagePDFBuilder.java
public void buildPDF(MimeMessage message, String replyURL, OutputStream pdfStream) throws DocumentException, MessagingException, IOException { Document document = createDocument(); PdfWriter pdfWriter = createPdfWriter(document, pdfStream); document.open();//w ww .j av a2 s . c o m String[] froms = null; try { froms = EmailAddressUtils.addressesToStrings(message.getFrom(), true /* mime decode */); } catch (MessagingException e) { logger.warn("From address is not a valid email address."); } if (froms != null) { for (String from : froms) { document.addAuthor(from); } } String subject = null; try { subject = message.getSubject(); } catch (MessagingException e) { logger.error("Error getting subject.", e); } if (subject != null) { document.addSubject(subject); document.addTitle(subject); } String[] tos = null; try { tos = EmailAddressUtils.addressesToStrings(message.getRecipients(RecipientType.TO), true /* mime decode */); } catch (MessagingException e) { logger.warn("To is not a valid email address."); } String[] ccs = null; try { ccs = EmailAddressUtils.addressesToStrings(message.getRecipients(RecipientType.CC), true /* mime decode */); } catch (MessagingException e) { logger.warn("CC is not a valid email address."); } Date sentDate = null; try { sentDate = message.getSentDate(); } catch (MessagingException e) { logger.error("Error getting sent date.", e); } Collection<Part> attachments = new LinkedList<Part>(); String body = BodyPartUtils.getPlainBodyAndAttachments(message, attachments); attachments = preprocessAttachments(attachments); if (body == null) { body = MISSING_BODY; } /* * PDF does not have tab support so we convert tabs to spaces */ body = StringReplaceUtils.replaceTabsWithSpaces(body, tabWidth); PdfPTable headerTable = new PdfPTable(2); headerTable.setHorizontalAlignment(Element.ALIGN_LEFT); headerTable.setWidthPercentage(100); headerTable.setWidths(new int[] { 1, 6 }); headerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER); Font headerFont = createHeaderFont(); FontSelector headerFontSelector = createHeaderFontSelector(); PdfPCell cell = new PdfPCell(new Paragraph("From:", headerFont)); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); headerTable.addCell(cell); String decodedFroms = StringUtils.defaultString(StringUtils.join(froms, ", ")); headerTable.addCell(headerFontSelector.process(decodedFroms)); cell = new PdfPCell(new Paragraph("To:", headerFont)); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); headerTable.addCell(cell); headerTable.addCell(headerFontSelector.process(StringUtils.defaultString(StringUtils.join(tos, ", ")))); cell = new PdfPCell(new Paragraph("CC:", headerFont)); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); headerTable.addCell(cell); headerTable.addCell(headerFontSelector.process(StringUtils.defaultString(StringUtils.join(ccs, ", ")))); cell = new PdfPCell(new Paragraph("Subject:", headerFont)); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); headerTable.addCell(cell); headerTable.addCell(headerFontSelector.process(StringUtils.defaultString(subject))); cell = new PdfPCell(new Paragraph("Date:", headerFont)); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); headerTable.addCell(cell); headerTable.addCell(ObjectUtils.toString(sentDate)); cell = new PdfPCell(new Paragraph("Attachments:", headerFont)); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); headerTable.addCell(cell); headerTable .addCell(headerFontSelector.process(StringUtils.defaultString(getAttachmentHeader(attachments)))); document.add(headerTable); if (replyURL != null) { addReplyLink(document, replyURL); } /* * Body table will contain the body of the message */ PdfPTable bodyTable = new PdfPTable(1); bodyTable.setWidthPercentage(100f); bodyTable.setSplitLate(false); bodyTable.setSpacingBefore(15f); bodyTable.setHorizontalAlignment(Element.ALIGN_LEFT); addBodyAndAttachments(pdfWriter, document, bodyTable, body, attachments); Phrase footer = new Phrase(FOOTER_TEXT); PdfContentByte cb = pdfWriter.getDirectContent(); ColumnText.showTextAligned(cb, Element.ALIGN_RIGHT, footer, document.right(), document.bottom(), 0); document.close(); }
From source file:com.zimbra.cs.zclient.ZMailboxUtil.java
private void addMessage(String folderId, String flags, String tags, long date, File file, boolean validate) throws ServiceException, IOException { //String aid = mMbox.uploadAttachments(new File[] {file}, 5000); InputStream in = new BufferedInputStream(new FileInputStream(file)); // Buffering required for gzip check long sizeHint = -1; if (ByteUtil.isGzipped(in)) { in = new GZIPInputStream(in); } else {/*from ww w. j a v a 2 s . c o m*/ sizeHint = file.length(); } byte[] data = ByteUtil.getContent(in, (int) sizeHint); if (validate && !EmailUtil.isRfc822Message(new ByteArrayInputStream(data))) { throw ZClientException.CLIENT_ERROR(file.getPath() + " does not contain a valid RFC 822 message", null); } try { if (date == -1) { MimeMessage mm = new ZMimeMessage(mSession, new SharedByteArrayInputStream(data)); Date d = mm.getSentDate(); if (d != null) date = d.getTime(); else date = 0; } } catch (MessagingException e) { date = 0; } String id = mMbox.addMessage(folderId, flags, tags, date, data, false); stdout.format("%s (%s)%n", id, file.getPath()); }
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 w ww . j a va 2s . c o m * @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; }