List of usage examples for javax.mail Message getSubject
public abstract String getSubject() throws MessagingException;
From source file:de.kp.ames.web.function.access.imap.ImapConsumer.java
/** * @param m/*from w w w .j a va 2 s . c om*/ * @return * @throws Exception */ private String mail2HTML(Message m) throws Exception { /* * Date & subject */ String date = m.getSentDate().toString(); String subject = m.getSubject(); /* * Body */ String body = getBody(m); /* * From */ String from = ""; Address[] addresses = m.getFrom(); for (Address address : addresses) { InternetAddress internetAddress = (InternetAddress) address; from = internetAddress.getPersonal(); } return HtmlRenderer.mail2HTML(from, date, subject, body); }
From source file:FolderModel.java
protected String[] getCachedData(int row) { if (cached[row] == null) { try {//w ww . ja v a 2 s . com Message m = messages[row]; String[] theData = new String[4]; // Date Date date = m.getSentDate(); if (date == null) { theData[0] = "Unknown"; } else { theData[0] = date.toString(); } // From Address[] adds = m.getFrom(); if (adds != null && adds.length != 0) { theData[1] = adds[0].toString(); } else { theData[1] = ""; } // Subject String subject = m.getSubject(); if (subject != null) { theData[2] = subject; } else { theData[2] = "(No Subject)"; } cached[row] = theData; } catch (MessagingException e) { e.printStackTrace(); } } return cached[row]; }
From source file:com.jaeksoft.searchlib.crawler.mailbox.crawler.MailboxAbstractCrawler.java
final public void readMessage(IndexDocument crawlIndexDocument, IndexDocument parserIndexDocument, Folder folder, Message message, String id) throws Exception { crawlIndexDocument.addString(MailboxFieldEnum.message_id.name(), id); crawlIndexDocument.addString(MailboxFieldEnum.message_number.name(), Integer.toString(message.getMessageNumber())); if (message instanceof MimeMessage) crawlIndexDocument.addString(MailboxFieldEnum.content_id.name(), ((MimeMessage) message).getContentID()); crawlIndexDocument.addString(MailboxFieldEnum.subject.name(), message.getSubject()); putAddresses(crawlIndexDocument, message.getFrom(), MailboxFieldEnum.from_address.name(), MailboxFieldEnum.from_personal.name()); putAddresses(crawlIndexDocument, message.getReplyTo(), MailboxFieldEnum.reply_to_address.name(), MailboxFieldEnum.reply_to_personal.name()); putAddresses(crawlIndexDocument, message.getRecipients(RecipientType.TO), MailboxFieldEnum.recipient_to_address.name(), MailboxFieldEnum.recipient_to_personal.name()); putAddresses(crawlIndexDocument, message.getRecipients(RecipientType.CC), MailboxFieldEnum.recipient_cc_address.name(), MailboxFieldEnum.recipient_cc_personal.name()); putAddresses(crawlIndexDocument, message.getRecipients(RecipientType.BCC), MailboxFieldEnum.recipient_bcc_address.name(), MailboxFieldEnum.recipient_bcc_personal.name()); Date dt = message.getSentDate(); if (dt != null) crawlIndexDocument.addString(MailboxFieldEnum.send_date.name(), dt.toString()); dt = message.getReceivedDate();/*from ww w .j a va 2s. c o m*/ if (dt != null) crawlIndexDocument.addString(MailboxFieldEnum.received_date.name(), dt.toString()); if (message.isSet(Flag.ANSWERED)) crawlIndexDocument.addString(MailboxFieldEnum.flags.name(), "ANSWERED"); if (message.isSet(Flag.DELETED)) crawlIndexDocument.addString(MailboxFieldEnum.flags.name(), "DELETED"); if (message.isSet(Flag.DRAFT)) crawlIndexDocument.addString(MailboxFieldEnum.flags.name(), "DRAFT"); if (message.isSet(Flag.FLAGGED)) crawlIndexDocument.addString(MailboxFieldEnum.flags.name(), "FLAGGED"); if (message.isSet(Flag.SEEN)) crawlIndexDocument.addString(MailboxFieldEnum.flags.name(), "SEEN"); if (message instanceof MimeMessage) { MimeMessageParser mimeMessageParser = new MimeMessageParser((MimeMessage) message).parse(); crawlIndexDocument.addString(MailboxFieldEnum.html_content.name(), mimeMessageParser.getHtmlContent()); crawlIndexDocument.addString(MailboxFieldEnum.plain_content.name(), mimeMessageParser.getPlainContent()); for (DataSource dataSource : mimeMessageParser.getAttachmentList()) { crawlIndexDocument.addString(MailboxFieldEnum.email_attachment_name.name(), dataSource.getName()); crawlIndexDocument.addString(MailboxFieldEnum.email_attachment_type.name(), dataSource.getContentType()); if (parserSelector == null) continue; Parser attachParser = parserSelector.parseStream(null, 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) crawlIndexDocument.addFieldIndexDocument(MailboxFieldEnum.email_attachment_content.name(), parserResult.getParserDocument()); } } }
From source file:nz.net.orcon.kanban.automation.actions.EmailReceiverAction.java
public void generateMailNotification(String mailStoreProtocol, String mailStoreHost, String mailStoreUserName, String mailStorePassword, String notificationType, String fromFilter, String subjectFilter) throws Exception { Session session = getMailStoreSession(mailStoreProtocol, mailStoreHost, mailStoreUserName, mailStorePassword);/* www.j a v a 2 s. c o m*/ try { // connects to the message store Store store = session.getStore(mailStoreProtocol); store.connect(mailStoreHost, mailStoreUserName, mailStorePassword); logger.info("connected to message store"); // opens the inbox folder Folder folderInbox = store.getFolder("INBOX"); folderInbox.open(Folder.READ_WRITE); // check if fromFilter is specified List<String> fromFilterList = null; if (StringUtils.isNotBlank(fromFilter)) { String[] fromFilterArray = StringUtils.split(fromFilter, "|"); fromFilterList = Arrays.asList(fromFilterArray); } // check if subjectFilter is specified List<String> subjectFilterList = null; if (StringUtils.isNotBlank(subjectFilter)) { String[] subjectFilterArray = StringUtils.split(subjectFilter, "|"); subjectFilterList = Arrays.asList(subjectFilterArray); } Map<String, Object> context = new HashMap<String, Object>(); // fetches new messages from server Message[] messages = folderInbox.getMessages(); for (int i = 0; i < messages.length; i++) { Message msg = messages[i]; Address[] fromAddress = msg.getFrom(); String address = fromAddress[0].toString(); String from = extractFromAddress(address); if (StringUtils.isBlank(from)) { logger.warn("From Address is not proper " + from); return; } boolean isValidFrom = isValidMatch(fromFilterList, from); // filter based on fromFilter specified if (null == fromFilterList || isValidFrom) { String subject = msg.getSubject(); boolean isValidSubject = isValidMatch(subjectFilterList, subject); if (null == subjectFilterList || isValidSubject) { String toList = parseAddresses(msg.getRecipients(RecipientType.TO)); String ccList = parseAddresses(msg.getRecipients(RecipientType.CC)); String sentDate = msg.getSentDate().toString(); String messageContent = ""; try { Object content = msg.getContent(); if (content != null) { messageContent = content.toString(); } } catch (Exception ex) { messageContent = "[Error downloading content]"; ex.printStackTrace(); } context.put("from", from); context.put("to", toList); context.put("cc", ccList); context.put("subject", subject); context.put("messagebody", messageContent); context.put("sentdate", sentDate); notificationController.createNotification(notificationType, context); msg.setFlag(Flag.DELETED, true); } else { logger.warn("subjectFilter doesn't match"); } } else { logger.warn("this email originated from " + address + " , which does not match fromAddress specified in the rule, it should be " + fromFilter.toString()); } } // disconnect and delete messages marked as DELETED folderInbox.close(true); store.close(); } catch (NoSuchProviderException ex) { logger.warn("No provider for protocol: " + mailStoreProtocol + " " + ex); } catch (MessagingException ex) { logger.error("Could not connect to the message store" + ex); } }
From source file:com.intranet.intr.inbox.EmpControllerInbox.java
public correoNoLeidos ltaRecibidos2(String name, int num) { correoNoLeidos lta = new correoNoLeidos(); Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); try {//from w w w. j av a 2s. c o m users u = usuarioService.getByLogin(name); Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("imap.1and1.es", u.getCorreoUsuario(), u.getCorreoContreasenna()); System.out.println("ola" + store); Folder inbox = store.getFolder("Inbox"); inbox.open(Folder.READ_ONLY); Calendar fecha3 = Calendar.getInstance(); fecha3.roll(Calendar.MONTH, false); Message msg[] = inbox.search(new ReceivedDateTerm(ComparisonTerm.GT, fecha3.getTime())); //Message msg[] = inbox.getMessages(); System.out.println("MAILS: " + msg.length); for (Message message : msg) { try { if (num == message.getMessageNumber()) { //message.setFlag(Flags.Flag.SEEN, true); lta.setNum(message.getMessageNumber()); lta.setFecha(message.getSentDate().toString()); lta.setDe(message.getFrom()[0].toString()); lta.setAsunto(message.getSubject().toString()); correoNoLeidos co = new correoNoLeidos(); List<String> arc = new ArrayList<String>(); List<String> rar = new ArrayList<String>(); correoNoLeidos cc = analizaParteDeMensaje2(co, arc, rar, message); lta.setImagenes(cc.getImagenes()); lta.setRar(cc.getRar()); lta.setContenido(cc.getContenido()); String cont = ""; String contenido = ""; //lta.setContenido(analizaParteDeMensaje2(message)); } } catch (Exception e) { System.out.println("No Information"); } } } catch (MessagingException e) { System.out.println(e.toString()); } return lta; }
From source file:org.alfresco.repo.imap.ImapMessageTest.java
public void testEightBitMessage() throws Exception { Store lstore = session.getStore(PROTOCOL); lstore.connect(imapServer.getHost(), imapServer.getPort(), ADMIN_USER_NAME, ADMIN_USER_PASSWORD); String folderName = "Alfresco IMAP/" + IMAP_FOLDER_NAME; IMAPFolder lfolder = (IMAPFolder) lstore.getFolder(folderName); lfolder.open(Folder.READ_WRITE);/*from w ww .j a v a2 s. c o m*/ InputStream messageFileInputStream1 = null; InputStream messageFileInputStream2 = null; try { ClassPathResource fileResource = new ClassPathResource("imap/test-8bit-message.eml"); messageFileInputStream1 = new FileInputStream(fileResource.getFile()); Message message = new MimeMessage(Session.getDefaultInstance(new Properties()), messageFileInputStream1); String subject = message.getSubject(); // get original bytes for further comparation messageFileInputStream2 = new FileInputStream(fileResource.getFile()); byte[] original = ASCIIUtility.getBytes(messageFileInputStream2); Message[] messages = { message }; lfolder.appendMessages(messages); // The search is not implemented. // SearchTerm term = new HeaderTerm("X-Alfresco-Unique", "test8bit"); // messages = folder.search(term); // So wee need to get our test message's UID from the repo String messageXPath = companyHomePathInStore + "/" + NamespaceService.CONTENT_MODEL_PREFIX + ":" + IMAP_FOLDER_NAME + "/*[like(@cm:title, $cm:title, true)]"; QueryParameterDefinition[] params = new QueryParameterDefinition[1]; params[0] = new QueryParameterDefImpl(ContentModel.PROP_TITLE, serviceRegistry.getDictionaryService().getDataType(DataTypeDefinition.TEXT), true, subject); List<NodeRef> nodeRefs = searchService.selectNodes(storeRootNodeRef, messageXPath, params, namespaceService, true); // does the message exist assertEquals(1, nodeRefs.size()); NodeRef messageNodeRef = nodeRefs.get(0); // get message UID Long dbid = (Long) nodeService.getProperty(messageNodeRef, ContentModel.PROP_NODE_DBID); // fetch the massage RFC822DATA data = getRFC822Message(lfolder, dbid); assertNotNull("Can't fetch a message from the repositiry", data); byte[] processed = ASCIIUtility.getBytes(data.getByteArrayInputStream()); assertTrue("Original message doesn't coincide to the message processed by the repository", Arrays.equals(original, processed)); } finally { if (messageFileInputStream1 != null) messageFileInputStream1.close(); if (messageFileInputStream2 != null) messageFileInputStream2.close(); } // close connection lfolder.close(true); lstore.close(); }
From source file:com.ikon.util.MailUtils.java
/** * Import mail into openkm repository/*from ww w .j a va 2 s .c om*/ */ public static void importMail(String token, String mailPath, boolean grouping, Folder folder, Message msg, MailAccount ma, com.ikon.bean.Mail mail) throws DatabaseException, RepositoryException, AccessDeniedException, ItemExistsException, PathNotFoundException, MessagingException, VirusDetectedException, UserQuotaExceededException, IOException, ExtensionException, AutomationException { OKMRepository okmRepository = OKMRepository.getInstance(); String path = grouping ? createGroupPath(token, mailPath, mail.getReceivedDate()) : mailPath; if (ma.getMailProtocol().equals(MailAccount.PROTOCOL_POP3) || ma.getMailProtocol().equals(MailAccount.PROTOCOL_POP3S)) { mail.setPath(path + "/" + ((POP3Folder) folder).getUID(msg) + "-" + PathUtils.escape( (msg.getSubject() == null || msg.getSubject().isEmpty()) ? NO_SUBJECT : msg.getSubject())); } else { mail.setPath(path + "/" + ((IMAPFolder) folder).getUID(msg) + "-" + PathUtils.escape( (msg.getSubject() == null || msg.getSubject().isEmpty()) ? NO_SUBJECT : msg.getSubject())); } String newMailPath = PathUtils.getParent(mail.getPath()) + "/" + PathUtils.escape(PathUtils.getName(mail.getPath())); log.debug("newMailPath: {}", newMailPath); if (!okmRepository.hasNode(token, newMailPath)) { if (Config.REPOSITORY_NATIVE) { new DbMailModule().create(token, mail, ma.getUser()); } else { new JcrMailModule().create(token, mail, ma.getUser()); } try { addAttachments(token, mail, msg, ma.getUser()); } catch (UnsupportedMimeTypeException e) { log.warn(e.getMessage(), e); } catch (FileSizeExceededException e) { log.warn(e.getMessage(), e); } catch (UserQuotaExceededException e) { log.warn(e.getMessage(), e); } } }
From source file:org.springframework.integration.mail.ImapMailReceiverTests.java
@Test // INT-2991 filtered messages were marked SEEN public void receiveAndMarkAsReadDontDeleteFiltered() throws Exception { AbstractMailReceiver receiver = new ImapMailReceiver(); Message msg1 = mock(MimeMessage.class); Message msg2 = mock(MimeMessage.class); given(msg2.getSubject()).willReturn("foo"); // should not be marked seen Expression selectorExpression = new SpelExpressionParser() .parseExpression("subject == null OR !subject.equals('foo')"); receiver.setSelectorExpression(selectorExpression); receiver = receiveAndMarkAsReadDontDeleteGuts(receiver, msg1, msg2); verify(msg1, times(1)).setFlag(Flag.SEEN, true); verify(msg2, never()).setFlag(Flag.SEEN, true); verify(receiver, times(0)).deleteMessages((Message[]) Mockito.any()); }
From source file:org.apache.usergrid.rest.management.AdminUsersIT.java
@Test public void checkFormPasswordReset() throws Exception { // initiate password reset management().users().user(clientSetup.getUsername()).resetpw().post(new Form()); refreshIndex();// w w w. j av a 2 s . c om // create mocked inbox, get password reset email and extract token List<Message> inbox = Mailbox.get(clientSetup.getEmail()); assertFalse(inbox.isEmpty()); MockImapClient client = new MockImapClient("mockserver.com", "test-user-46", "somepassword"); client.processMail(); // Get email with confirmation token and extract token String token = null; Iterator<Message> msgIterator = inbox.iterator(); while (token == null && msgIterator.hasNext()) { Message msg = msgIterator.next(); if (msg.getSubject().equals("Password Reset")) { token = getTokenFromMessage(msg); } } assertNotNull(token); Form formData = new Form(); formData.param("token", token); formData.param("password1", "sesame"); formData.param("password2", "sesame"); String html = management().users().user(clientSetup.getUsername()).resetpw().getTarget().request() .post(javax.ws.rs.client.Entity.form(formData), String.class); assertTrue(html.contains("password set")); refreshIndex(); html = management().users().user(clientSetup.getUsername()).resetpw().post(formData); assertTrue(html.contains("invalid token")); }
From source file:org.apache.usergrid.rest.management.AdminUsersIT.java
@Test public void passwordResetIncorrectUserName() throws Exception { // initiate password reset management().users().user(clientSetup.getUsername()).resetpw().post(new Form()); refreshIndex();/*www. j a va 2 s .c om*/ // create mocked inbox, get password reset email and extract token List<Message> inbox = Mailbox.get(clientSetup.getEmail()); assertFalse(inbox.isEmpty()); MockImapClient client = new MockImapClient("mockserver.com", "test-user-47", "somepassword"); client.processMail(); // Get email with confirmation token and extract token String token = null; Iterator<Message> msgIterator = inbox.iterator(); while (token == null && msgIterator.hasNext()) { Message msg = msgIterator.next(); if (msg.getSubject().equals("Password Reset")) { token = getTokenFromMessage(msg); } } assertNotNull(token); Form formData = new Form(); formData.param("token", token); formData.param("password1", "sesame"); formData.param("password2", "sesame"); try { String html = management().users().user("mr_fatfinger").resetpw().getTarget().request() .post(javax.ws.rs.client.Entity.form(formData), String.class); fail("Password reset request should have failed"); } catch (BadRequestException expected) { String body = expected.getResponse().readEntity(String.class); assertTrue(body.contains("Could not find")); } String html = management().users().user(clientSetup.getUsername()).resetpw().getTarget().request() .post(javax.ws.rs.client.Entity.form(formData), String.class); assertTrue(html.contains("password set")); }