List of usage examples for javax.mail FetchProfile add
public void add(String headerName)
From source file:org.springframework.ws.transport.mail.monitor.AbstractMonitoringStrategy.java
/** * Fetches the specified messages from the specified folder. Default implementation {@link Folder#fetch(Message[], * FetchProfile) fetches} every {@link javax.mail.FetchProfile.Item}. * * @param folder the folder to fetch messages from * @param messages the messages to fetch * @throws MessagingException in case of JavMail errors *//* ww w . j ava2 s .c o m*/ protected void fetchMessages(Folder folder, Message[] messages) throws MessagingException { FetchProfile contentsProfile = new FetchProfile(); contentsProfile.add(FetchProfile.Item.ENVELOPE); contentsProfile.add(FetchProfile.Item.CONTENT_INFO); contentsProfile.add(FetchProfile.Item.FLAGS); folder.fetch(messages, contentsProfile); }
From source file:com.agiletec.plugins.jpwebmail.apsadmin.webmail.folder.WebmailAction.java
public List<Message> getMessages() throws Throwable { List<Message> messageList = null; try {// w ww .j av a 2s .c o m Folder folder = this.getCurrentFolder(); folder.open(Folder.READ_ONLY); CurrentFolderMessagesInfo folderInfos = (CurrentFolderMessagesInfo) this.getRequest().getSession() .getAttribute(CurrentFolderMessagesInfo.CURRENT_FOLDER_MESSAGES); //if (this.hasToReloadMessages(folder, folderInfos)) { Message messages[] = folder.getMessages(); FetchProfile profile = new FetchProfile(); profile.add(FetchProfile.Item.ENVELOPE); folder.fetch(messages, profile); this.setOpenedFolder(folder); messageList = Arrays.asList(messages); this.orderMessages(messageList); folderInfos = new CurrentFolderMessagesInfo(this.getCurrentFolderName(), messageList); this.getRequest().getSession().setAttribute(CurrentFolderMessagesInfo.CURRENT_FOLDER_MESSAGES, folderInfos); //} else { // messageList = folderInfos.getMessages(); //} } catch (Throwable t) { _logger.error("Error extracting messages", t); throw t; } return messageList; }
From source file:gmailclientfx.controllers.InboxController.java
public void fetchInbox() { ObservableList<MyMessage> data = FXCollections.observableArrayList(); stupacId.setCellValueFactory(new PropertyValueFactory<MyMessage, Integer>("TblId")); stupacNaslov.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Subject")); stupacPosiljatelj.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Sender")); stupacDatum.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("DateReceived")); Platform.runLater(() -> {/*from w w w . j av a 2 s. co m*/ inboxTable.setItems(data); }); inboxTable.setOnMousePressed(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { if (event.isPrimaryButtonDown() && event.getClickCount() == 2) { MyMessage selectedMsg = inboxTable.getSelectionModel().getSelectedItem(); PregledEmailaHelper.setMsg(selectedMsg); try { Parent root; FXMLLoader loader = new FXMLLoader(); loader.setLocation( getClass().getClassLoader().getResource("gmailclientfx/views/pregledEmaila.fxml")); root = loader.load(); Stage stage = new Stage(); stage.setScene(new Scene(root)); stage.setTitle(PregledEmailaHelper.getMsg().getSubject() + " - " + PregledEmailaHelper.getMsg().getSender()); stage.show(); PregledEmailaController pgec = loader.getController(); stage.setOnCloseRequest(new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent event) { pgec.bodyWebViewEngine.load(null); System.out.println("Closing form!"); } }); } catch (IOException ex) { Logger.getLogger(InboxController.class.getName()).log(Level.SEVERE, null, ex); } } } }); try { IMAPStore store = OAuth2Authenticator.connectToImap("imap.gmail.com", 993, GmailClient.getEmail(), GmailClient.getAccesToken(), true); Folder inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_WRITE); int getSeenCount = inbox.getMessageCount(); FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfileItem.FLAGS); fp.add(FetchProfileItem.CONTENT_INFO); fp.add("X-mailer"); MimeMessage[] seenMessages = (MimeMessage[]) inbox .search(new FlagTerm(new Flags(Flags.Flag.SEEN), true)); for (int i = 0; i < seenMessages.length; i++) { MyMessage msg = GmailClient.fetchMessage(seenMessages[i], i + 1, "INBOX"); data.add(msg); } MimeMessage[] unseenMessages = (MimeMessage[]) inbox .search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); for (int i = 0; i < unseenMessages.length; i++) { MyMessage msg = GmailClient.fetchMessage(unseenMessages[i], i + 1, "INBOX"); data.add(msg); } inbox.close(false); store.close(); } catch (Exception ex) { Logger.getLogger(InboxController.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.campware.dream.modules.scheduledjobs.Pop3Job.java
private void doReceiveMessages() throws Exception { String host = TurbineResources.getString("mail.pop3.host"); String username = TurbineResources.getString("mail.pop3.user"); String password = TurbineResources.getString("mail.pop3.password"); // Create empty properties Properties props = new Properties(); // Get session Session session = Session.getDefaultInstance(props, null); // Get the store Store store = session.getStore("pop3"); // Connect to store store.connect(host, username, password); // Get folder Folder folder = store.getFolder("INBOX"); // Open read-only folder.open(Folder.READ_WRITE);//w w w . ja v a 2s .c o m // Get attributes & flags for all messages // Message[] messages = folder.getMessages(); FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.FLAGS); fp.add("X-Mailer"); folder.fetch(messages, fp); // Process each message // Address fromAddress = new InternetAddress(); String from = new String(); String name = new String(); String email = new String(); String subject = new String(); String content = new String(); for (int i = 0; i < messages.length; i++) { email = ((InternetAddress) messages[i].getFrom()[0]).getAddress(); name = ((InternetAddress) messages[i].getFrom()[0]).getPersonal(); subject = messages[i].getSubject(); content = messages[i].getContent().toString(); DinboxEvent entry = new DinboxEvent(); Criteria criteria = new Criteria(); criteria.add(DistributorPeer.EMAIL, (Object) email, Criteria.EQUAL); if (DistributorPeer.doSelect(criteria).size() > 0) { Distributor myDistrib = (Distributor) DistributorPeer.doSelect(criteria).get(0); entry.setDistributorId(myDistrib.getDistributorId()); } else { if (name != null) { entry.setBody("From: " + name + " " + email + "\n\n" + content); } else { entry.setBody("From: " + email + "\n\n" + content); } } entry.setDinboxEventCode(getTempCode()); entry.setEventType(10); entry.setEventChannel(10); entry.setSubject(subject); entry.setIssuedDate(new Date()); entry.setCreatedBy("scheduler"); entry.setCreated(new Date()); entry.setModifiedBy("scheduler"); entry.setModified(new Date()); Connection conn = Transaction.begin(DinboxEventPeer.DATABASE_NAME); boolean success = false; try { entry.save(conn); entry.setDinboxEventCode(getRowCode("IE", entry.getDinboxEventId())); entry.save(conn); Transaction.commit(conn); success = true; } finally { if (!success) Transaction.safeRollback(conn); } messages[i].setFlag(Flags.Flag.DELETED, true); } // Close connection folder.close(true); store.close(); }
From source file:com.jaeksoft.searchlib.crawler.mailbox.crawler.MailboxAbstractCrawler.java
private void readMessagesFolder(Folder folder) throws MessagingException, IOException, SearchLibException { folder.open(Folder.READ_ONLY);/*w w w . jav a 2 s . c o m*/ String folderFullName = folder.getFullName(); try { int max = folder.getMessageCount(); int i = 0; final int buffer = item.getBufferSize(); while (i < max && !thread.isAborted()) { thread.setStatusInfo(CrawlStatus.CRAWL); int end = i + buffer; if (end > max) end = max; Message[] messages = folder.getMessages(i + 1, end); FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); folder.fetch(messages, fp); for (Message message : messages) { if (thread.isAborted()) break; i++; String messageId = getMessageId(folder, message); if (StringUtils.isEmpty(messageId)) continue; if (thread.isAlreadyIndexed(messageId)) { thread.incIgnored(); continue; } IndexDocument crawlIndexDocument = new IndexDocument(item.getLang()); IndexDocument parserIndexDocument = new IndexDocument(item.getLang()); crawlIndexDocument.addString(MailboxFieldEnum.folder.name(), folderFullName); try { readMessage(crawlIndexDocument, parserIndexDocument, folder, message, messageId); thread.addDocument(crawlIndexDocument, parserIndexDocument); } catch (Exception e) { Logging.warn(e); thread.incError(); } } } } finally { folder.close(false); } }
From source file:org.eurekastreams.server.service.email.ImapEmailIngester.java
/** * Ingests email from a mailbox./* w w w . j ava2s . c o m*/ */ public void execute() { // get message store Store store; try { long startTime = System.nanoTime(); store = storeFactory.getStore(); log.debug("Connected to mail store in {}ns", System.nanoTime() - startTime); } catch (MessagingException ex) { log.error("Error getting message store.", ex); return; } try { // get folders Folder inputFolder = store.getFolder(inputFolderName); if (!inputFolder.exists()) { log.error("Input folder {} does not exist.", inputFolderName); return; } Folder successFolder = null; if (StringUtils.isNotBlank(successFolderName)) { successFolder = store.getFolder(successFolderName); if (!successFolder.exists()) { log.error("Success folder {} does not exist.", successFolderName); return; } } Folder discardFolder = null; if (StringUtils.isNotBlank(discardFolderName)) { discardFolder = store.getFolder(discardFolderName); if (!discardFolder.exists()) { log.error("Discard folder {} does not exist.", discardFolderName); return; } } Folder errorFolder = null; if (StringUtils.isNotBlank(errorFolderName)) { errorFolder = store.getFolder(errorFolderName); if (!errorFolder.exists()) { log.error("Error folder {} does not exist.", errorFolderName); return; } } inputFolder.open(Folder.READ_WRITE); // fetch messages // Note: Not preloading CONTENT_INFO. For some reason, preloading the content info (IMAP BODYSTRUCTURE) // causes the call to getContent to return empty. (As if there was a bug where getContent saw the cached // body structure and thought that the content itself was cached, but I'd think a bug like that would have // been found by many people and fixed long ago, so I'm assuming it's something else.) FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); Message[] msgs = inputFolder.getMessages(); inputFolder.fetch(msgs, fp); log.debug("About to process {} messages", msgs.length); // process each message if (msgs.length > 0) { List<Message> successMessages = new ArrayList<Message>(); List<Message> errorMessages = new ArrayList<Message>(); List<Message> discardMessages = new ArrayList<Message>(); List<Message> responseMessages = new ArrayList<Message>(); for (int i = 0; i < msgs.length; i++) { Message message = msgs[i]; try { boolean processed = messageProcessor.execute(message, responseMessages); (processed ? successMessages : discardMessages).add(message); } catch (Exception ex) { log.error("Failed to process email message.", ex); errorMessages.add(message); } } // send response messages for (Message responseMessage : responseMessages) { emailerFactory.sendMail(responseMessage); } // move and purge messages if (successFolder != null && !successMessages.isEmpty()) { inputFolder.copyMessages(successMessages.toArray(new Message[successMessages.size()]), successFolder); } if (discardFolder != null && !discardMessages.isEmpty()) { inputFolder.copyMessages(discardMessages.toArray(new Message[discardMessages.size()]), discardFolder); } if (errorFolder != null && !errorMessages.isEmpty()) { inputFolder.copyMessages(errorMessages.toArray(new Message[errorMessages.size()]), errorFolder); } for (int i = 0; i < msgs.length; i++) { msgs[i].setFlag(Flag.DELETED, true); } log.info("{} messages processed: {} successful, {} discarded, {} failed.", new Object[] { msgs.length, successMessages.size(), discardMessages.size(), errorMessages.size() }); } // close folder inputFolder.close(true); } catch (MessagingException ex) { log.error("Error ingesting email.", ex); } catch (Exception ex) { log.error("Error ingesting email.", ex); } finally { // close store try { store.close(); } catch (MessagingException ex) { log.error("Error closing message store.", ex); } } }
From source file:org.apache.hupa.server.handler.AbstractFetchMessagesHandler.java
protected ArrayList<org.apache.hupa.shared.data.Message> convert(int offset, com.sun.mail.imap.IMAPFolder folder, Message[] messages) throws MessagingException { ArrayList<org.apache.hupa.shared.data.Message> mList = new ArrayList<org.apache.hupa.shared.data.Message>(); // Setup fetchprofile to limit the stuff which is fetched FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.FLAGS);/*from ww w . j a va 2s . com*/ fp.add(FetchProfile.Item.CONTENT_INFO); fp.add(UIDFolder.FetchProfileItem.UID); folder.fetch(messages, fp); // loop over the fetched messages for (int i = 0; i < messages.length && i < offset; i++) { org.apache.hupa.shared.data.Message msg = new org.apache.hupa.shared.data.Message(); Message m = messages[i]; String from = null; if (m.getFrom() != null && m.getFrom().length > 0) { from = MessageUtils.decodeText(m.getFrom()[0].toString()); } msg.setFrom(from); String replyto = null; if (m.getReplyTo() != null && m.getReplyTo().length > 0) { replyto = MessageUtils.decodeText(m.getReplyTo()[0].toString()); } msg.setReplyto(replyto); ArrayList<String> to = new ArrayList<String>(); // Add to addresses Address[] toArray = m.getRecipients(RecipientType.TO); if (toArray != null) { for (Address addr : toArray) { String mailTo = MessageUtils.decodeText(addr.toString()); to.add(mailTo); } } msg.setTo(to); // Check if a subject exist and if so decode it String subject = m.getSubject(); if (subject != null) { subject = MessageUtils.decodeText(subject); } msg.setSubject(subject); // Add cc addresses Address[] ccArray = m.getRecipients(RecipientType.CC); ArrayList<String> cc = new ArrayList<String>(); if (ccArray != null) { for (Address addr : ccArray) { String mailCc = MessageUtils.decodeText(addr.toString()); cc.add(mailCc); } } msg.setCc(cc); userPreferences.addContact(from); userPreferences.addContact(to); userPreferences.addContact(replyto); userPreferences.addContact(cc); // Using sentDate since received date is not useful in the view when using fetchmail msg.setReceivedDate(m.getSentDate()); // Add flags ArrayList<IMAPFlag> iFlags = JavamailUtil.convert(m.getFlags()); ArrayList<Tag> tags = new ArrayList<Tag>(); for (String flag : m.getFlags().getUserFlags()) { if (flag.startsWith(Tag.PREFIX)) { tags.add(new Tag(flag.substring(Tag.PREFIX.length()))); } } msg.setUid(folder.getUID(m)); msg.setFlags(iFlags); msg.setTags(tags); try { msg.setHasAttachments(hasAttachment(m)); } catch (MessagingException e) { logger.debug("Unable to identify attachments in message UID:" + msg.getUid() + " subject:" + msg.getSubject() + " cause:" + e.getMessage()); logger.info(""); } mList.add(0, msg); } return mList; }
From source file:com.abid_mujtaba.fetchheaders.models.Account.java
public SparseArray<Email> fetchEmails() throws MessagingException // Fetches messages from account and uses them to create an array of Email objects. Catches connection exception and re-throws them up the chain. { Properties props = new Properties(); props.setProperty("mail.store.protocol", "imaps"); props.setProperty("mail.imaps.host", mHost); props.setProperty("mail.imaps.port", "993"); props.setProperty("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // Uses SSL to secure communication props.setProperty("mail.imaps.socketFactory.fallback", "false"); Session imapSession = Session.getInstance(props); try {/*from w w w . ja v a2 s. com*/ Store store = imapSession.getStore("imaps"); // Connect to server by sending username and password: store.connect(mHost, mUsername, mPassword); mInbox = store.getFolder("Inbox"); mInbox.open(Folder.READ_WRITE); // Open Inbox as read-write since we will be deleting emails later mTrash = store.getFolder("Trash"); if (!mTrash.exists()) { mTrash = store.getFolder("[Gmail]/Trash"); // If a folder labelled "Trash" doesn't exist we attempt to check if it is a Gmail account whose trash folder is differently named mUsesLabels = true; // Set flag to indicate that this account uses Labels rather than folders a la Gmail if (!mTrash.exists()) { mTrash = null; // No trash folder found. Emails will be deleted directly mUsesLabels = false; } } int num = mInbox.getMessageCount(); // Get number of messages in the Inbox if (num > mMaxNumOfEmails) { mMessages = mInbox.getMessages(num - mMaxNumOfEmails + 1, num); // Fetch latest mMaxNumOfEmails emails (seen and unseen both). The oldest email is indexed as 1 and so on. } else { mMessages = mInbox.getMessages(); } FetchProfile fp = new FetchProfile(); fp.add(IMAPFolder.FetchProfileItem.HEADERS); // Fetch header data fp.add(FetchProfile.Item.FLAGS); // Fetch flags mInbox.fetch(mMessages, fp); // Now that the messages have been fetched using the FetchProfile (that is the necessary information has been fetched with them) we sort the message in reverse chronological order Arrays.sort(mMessages, new MessageComparator()); // The sort is accomplished using an instance of a custom comparator that compares messages using DateSent mEmails = new SparseArray<Email>(); for (int ii = 0; ii < mMessages.length; ii++) { Email email = new Email(mMessages[ii]); mEmails.put(ii, email); } return mEmails; } catch (MessagingException e) { Resources.Loge("Exception while attempting to connect to mail server", e); throw e; } // The two above exceptions are caught by this one if they are not explicitly stated above. }
From source file:org.springframework.integration.mail.AbstractMailReceiver.java
/** * Fetches the specified messages from this receiver's folder. Default * implementation {@link Folder#fetch(Message[], FetchProfile) fetches} * every {@link javax.mail.FetchProfile.Item}. * * @param messages the messages to fetch * @throws MessagingException in case of JavaMail errors *///w w w . j a va 2s . c o m protected void fetchMessages(Message[] messages) throws MessagingException { FetchProfile contentsProfile = new FetchProfile(); contentsProfile.add(FetchProfile.Item.ENVELOPE); contentsProfile.add(FetchProfile.Item.CONTENT_INFO); contentsProfile.add(FetchProfile.Item.FLAGS); this.folder.fetch(messages, contentsProfile); }
From source file:org.campware.cream.modules.scheduledjobs.Pop3Job.java
private void doReceiveMessages() throws Exception { log.debug("Checking mail "); String host = Turbine.getConfiguration().getString("mail.pop3.host"); String username = Turbine.getConfiguration().getString("mail.pop3.user"); String password = Turbine.getConfiguration().getString("mail.pop3.password"); // Create empty properties Properties props = new Properties(); // Get session Session session = Session.getDefaultInstance(props, null); // Get the store Store store = session.getStore("pop3"); // Connect to store store.connect(host, username, password); // Get folder Folder folder = store.getFolder("INBOX"); // Open read-only folder.open(Folder.READ_WRITE);/*from w w w .jav a 2 s . c o m*/ // Get attributes & flags for all messages // Message[] messages = folder.getMessages(); FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.FLAGS); fp.add("X-Mailer"); folder.fetch(messages, fp); for (int i = 0; i < messages.length; i++) { log.debug("Retrieving message " + i); // Process each message // InboxEvent entry = new InboxEvent(); Address fromAddress = new InternetAddress(); String from = new String(); String name = new String(); String email = new String(); String replyTo = new String(); String subject = new String(); String content = new String(); Date sentDate = new Date(); int emailformat = 10; Message m = messages[i]; // and now, handle the content Object o = m.getContent(); // find content type if (m.isMimeType("text/plain")) { content = "<PRE style=\"font-size: 12px;\">" + (String) o + "</PRE>"; emailformat = 10; } else if (m.isMimeType("text/html")) { content = (String) o; emailformat = 20; } else if (m.isMimeType("text/*")) { content = (String) o; emailformat = 30; } else if (m.isMimeType("multipart/alternative")) { try { content = handleAlternative(o, content); emailformat = 20; } catch (Exception ex) { content = "Problem with the message format. Messssage has left on the email server."; emailformat = 50; log.error(ex.getMessage(), ex); } } else if (m.isMimeType("multipart/*")) { try { content = handleMulitipart(o, content, entry); emailformat = 40; } catch (Exception ex) { content = "Problem with the message format. Messssage has left on the email server."; emailformat = 50; log.error(ex.getMessage(), ex); } } else { content = "Problem with the message format. Messssage has left on the email server."; emailformat = 50; log.debug("Could not handle properly"); } email = ((InternetAddress) m.getFrom()[0]).getAddress(); name = ((InternetAddress) m.getFrom()[0]).getPersonal(); replyTo = ((InternetAddress) m.getReplyTo()[0]).getAddress(); sentDate = m.getSentDate(); subject = m.getSubject(); log.debug("Got message " + email + " " + name + " " + subject + " " + content); Criteria contcrit = new Criteria(); contcrit.add(ContactPeer.EMAIL, (Object) email, Criteria.EQUAL); if (ContactPeer.doSelect(contcrit).size() > 0) { log.debug("From known contact"); Contact myContact = (Contact) ContactPeer.doSelect(contcrit).get(0); entry.setCustomerId(myContact.getCustomerId()); entry.setContactId(myContact.getContactId()); } else { // find if customer exists Criteria criteria = new Criteria(); criteria.add(CustomerPeer.EMAIL, (Object) email, Criteria.EQUAL); if (CustomerPeer.doSelect(criteria).size() > 0) { log.debug("From known customer"); Customer myDistrib = (Customer) CustomerPeer.doSelect(criteria).get(0); entry.setCustomerId(myDistrib.getCustomerId()); } } entry.setInboxEventCode(getTempCode()); entry.setEventType(10); entry.setEventChannel(10); entry.setEmailFormat(emailformat); entry.setSubject(subject); entry.setSenderEmail(email); entry.setSenderName(name); entry.setSenderReplyTo(replyTo); entry.setSentTime(sentDate); entry.setBody(content); entry.setIssuedDate(new Date()); entry.setCreatedBy("system"); entry.setCreated(new Date()); entry.setModifiedBy("system"); entry.setModified(new Date()); Connection conn = Transaction.begin(InboxEventPeer.DATABASE_NAME); boolean success = false; try { entry.save(conn); entry.setInboxEventCode(getRowCode("IE", entry.getInboxEventId())); entry.save(conn); Transaction.commit(conn); success = true; } finally { log.debug("Succcessfully stored in db: " + success); if (!success) Transaction.safeRollback(conn); } if (emailformat != 50) { m.setFlag(Flags.Flag.DELETED, true); } } // Close pop3 connection folder.close(true); store.close(); }