List of usage examples for javax.mail Store connect
public void connect(String host, String user, String password) throws MessagingException
From source file:com.openkm.util.MailUtils.java
/** * Import messages/* w ww . j a v a 2 s . c om*/ * http://www.jguru.com/faq/view.jsp?EID=26898 * * == Using Unique Identifier (UIDL) == * Mail server assigns an unique identifier for every email in the same account. You can get as UIDL * for every email by MailInfo.UIDL property. To avoid receiving the same email twice, the best way is * storing the UIDL of email retrieved to a text file or database. Next time before you retrieve email, * compare your local uidl list with remote uidl. If this uidl exists in your local uidl list, don't * receive it; otherwise receive it. * * == Different property of UIDL in POP3 and IMAP4 == * UIDL is always unique in IMAP4 and it is always an incremental integer. UIDL in POP3 can be any valid * asc-ii characters, and an UIDL may be reused by POP3 server if email with this UIDL has been deleted * from the server. Hence you are advised to remove the uidl from your local uidl list if that uidl is * no longer exist on the POP3 server. * * == Remarks == * You should create different local uidl list for different email account, because the uidl is only * unique for the same account. */ public static String importMessages(String token, MailAccount ma) throws PathNotFoundException, ItemExistsException, VirusDetectedException, AccessDeniedException, RepositoryException, DatabaseException, UserQuotaExceededException, ExtensionException, AutomationException { log.debug("importMessages({}, {})", new Object[] { token, ma }); Session session = Session.getDefaultInstance(getProperties()); String exceptionMessage = null; try { // Open connection Store store = session.getStore(ma.getMailProtocol()); store.connect(ma.getMailHost(), ma.getMailUser(), ma.getMailPassword()); Folder folder = store.getFolder(ma.getMailFolder()); folder.open(Folder.READ_WRITE); Message messages[] = null; if (folder instanceof IMAPFolder) { // IMAP folder UIDs begins at 1 and are supposed to be sequential. // Each folder has its own UIDs sequence, not is a global one. messages = ((IMAPFolder) folder).getMessagesByUID(ma.getMailLastUid() + 1, UIDFolder.LASTUID); } else { messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); } for (int i = 0; i < messages.length; i++) { Message msg = messages[i]; log.info("======= ======= {} ======= =======", i); log.info("Subject: {}", msg.getSubject()); log.info("From: {}", msg.getFrom()); log.info("Received: {}", msg.getReceivedDate()); log.info("Sent: {}", msg.getSentDate()); com.openkm.bean.Mail mail = messageToMail(msg); if (ma.getMailFilters().isEmpty()) { log.debug("Import in compatibility mode"); String mailPath = getUserMailPath(ma.getUser()); importMail(token, mailPath, true, folder, msg, ma, mail); } else { for (MailFilter mf : ma.getMailFilters()) { log.debug("MailFilter: {}", mf); if (checkRules(mail, mf.getFilterRules())) { String mailPath = mf.getPath(); importMail(token, mailPath, mf.isGrouping(), folder, msg, ma, mail); } } } // Set message as seen if (ma.isMailMarkSeen()) { msg.setFlag(Flags.Flag.SEEN, true); } else { msg.setFlag(Flags.Flag.SEEN, false); } // Delete read mail if requested if (ma.isMailMarkDeleted()) { msg.setFlag(Flags.Flag.DELETED, true); } // Set lastUid if (folder instanceof IMAPFolder) { long msgUid = ((IMAPFolder) folder).getUID(msg); log.info("Message UID: {}", msgUid); ma.setMailLastUid(msgUid); MailAccountDAO.update(ma); } } // Close connection log.debug("Expunge: {}", ma.isMailMarkDeleted()); folder.close(ma.isMailMarkDeleted()); store.close(); } catch (NoSuchProviderException e) { log.error(e.getMessage(), e); exceptionMessage = e.getMessage(); } catch (MessagingException e) { log.error(e.getMessage(), e); exceptionMessage = e.getMessage(); } catch (IOException e) { log.error(e.getMessage(), e); exceptionMessage = e.getMessage(); } log.debug("importMessages: {}", exceptionMessage); return exceptionMessage; }
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);/*from www .j a v a 2s .co 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:org.usergrid.rest.management.RegistrationIT.java
private Message[] getMessages(String host, String user, String password) throws MessagingException, IOException { Session session = Session.getDefaultInstance(new Properties()); Store store = session.getStore("imap"); store.connect(host, user, password); Folder folder = store.getFolder("inbox"); folder.open(Folder.READ_ONLY);//from ww w. j a v a 2 s . c om Message[] msgs = folder.getMessages(); for (Message m : msgs) { logger.info("Subject: " + m.getSubject()); logger.info("Body content 0 " + (String) ((MimeMultipart) m.getContent()).getBodyPart(0).getContent()); logger.info("Body content 1 " + (String) ((MimeMultipart) m.getContent()).getBodyPart(1).getContent()); } return msgs; }
From source file:org.apache.usergrid.rest.management.RegistrationIT.java
private Message[] getMessages(String host, String user, String password) throws MessagingException, IOException { Session session = Session.getDefaultInstance(new Properties()); Store store = session.getStore("imap"); store.connect(host, user, password); Folder folder = store.getFolder("inbox"); folder.open(Folder.READ_ONLY);//from www .ja v a2 s . c om Message[] msgs = folder.getMessages(); for (Message m : msgs) { logger.info("Subject: " + m.getSubject()); logger.info("Body content 0 " + ((MimeMultipart) m.getContent()).getBodyPart(0).getContent()); logger.info("Body content 1 " + ((MimeMultipart) m.getContent()).getBodyPart(1).getContent()); } return msgs; }
From source file:nz.net.orcon.kanban.automation.actions.EmailReceiverAction.java
public void downloadEmails(String mailStoreProtocol, String mailStoreHost, String mailStoreUserName, String mailStorePassword) throws IOException { Session session = getMailStoreSession(mailStoreProtocol, mailStoreHost, mailStoreUserName, mailStorePassword);/* w ww. j a v a2 s. com*/ 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_ONLY); // 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 from = fromAddress[0].toString(); String subject = msg.getSubject(); String toList = parseAddresses(msg.getRecipients(RecipientType.TO)); String ccList = parseAddresses(msg.getRecipients(RecipientType.CC)); String sentDate = msg.getSentDate().toString(); String contentType = msg.getContentType(); String messageContent = ""; if (contentType.contains("text/plain") || contentType.contains("text/html")) { try { Object content = msg.getContent(); if (content != null) { messageContent = content.toString(); } } catch (Exception ex) { messageContent = "[Error downloading content]"; ex.printStackTrace(); } } // print out details of each message System.out.println("Message #" + (i + 1) + ":"); System.out.println("\t From: " + from); System.out.println("\t To: " + toList); System.out.println("\t CC: " + ccList); System.out.println("\t Subject: " + subject); System.out.println("\t Sent Date: " + sentDate); System.out.println("\t Message: " + messageContent); } // disconnect folderInbox.close(false); 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:org.syncope.core.notification.NotificationTest.java
private boolean verifyMail(final String sender, final String subject) { LOG.info("Waiting for notification to be sent..."); try {/*from w ww.j a va 2 s . c o m*/ Thread.sleep(10000); } catch (InterruptedException e) { } boolean found = false; try { Session session = Session.getDefaultInstance(System.getProperties()); Store store = session.getStore("pop3"); store.connect(pop3Host, mailAddress, mailPassword); Folder inbox = store.getFolder("INBOX"); assertNotNull(inbox); inbox.open(Folder.READ_WRITE); Message[] messages = inbox.getMessages(); for (int i = 0; i < messages.length; i++) { if (sender.equals(messages[i].getFrom()[0].toString()) && subject.equals(messages[i].getSubject())) { found = true; messages[i].setFlag(Flag.DELETED, true); } } inbox.close(true); store.close(); } catch (Throwable t) { LOG.error("Unexpected exception", t); fail("Unexpected exception while fetching e-mail"); } return found; }
From source file:org.alfresco.repo.imap.RemoteLoadTester.java
public void testMailbox() { logger.info("Getting folder..."); long t = System.currentTimeMillis(); // Create empty properties Properties props = new Properties(); props.setProperty("mail.imap.partialfetch", "false"); // Get session Session session = Session.getDefaultInstance(props, null); Store store = null; Folder folder = null;/* w w w . j a va 2s . c o m*/ try { // Get the store store = session.getStore("imap"); store.connect(REMOTE_HOST, USER_NAME, USER_PASSWORD); // Get folder folder = store.getFolder(TEST_FOLDER_NAME); folder.open(Folder.READ_ONLY); // Get directory Message message[] = folder.getMessages(); for (int i = 0, n = message.length; i < n; i++) { message[i].getAllHeaders(); Address[] from = message[i].getFrom(); System.out.print(i + ": "); if (from != null) { System.out.print(message[i].getFrom()[0] + "\t"); } System.out.println(message[i].getSubject()); Object content = message[i].getContent(); if (content instanceof MimeMultipart) { for (int j = 0, m = ((MimeMultipart) content).getCount(); j < m; j++) { BodyPart part = ((MimeMultipart) content).getBodyPart(j); Object partContent = part.getContent(); if (partContent instanceof String) { String body = (String) partContent; } else if (partContent instanceof FilterInputStream) { FilterInputStream fis = (FilterInputStream) partContent; BufferedInputStream bis = new BufferedInputStream(fis); /* while (bis.available() > 0) { bis.read(); }*/ byte[] bytes = new byte[524288]; while (bis.read(bytes) != -1) { } bis.close(); fis.close(); } } } int nn = 0; } t = System.currentTimeMillis() - t; logger.info("Time: " + t + " ms (" + t / 1000 + " s)"); logger.info("Length: " + message.length); } catch (Exception e) { logger.error(e.getMessage(), e); fail(e.getMessage()); } finally { // Close connection try { if (folder != null) { folder.close(false); } } catch (MessagingException e) { logger.error(e.getMessage(), e); fail(e.getMessage()); } try { if (store != null) { store.close(); } } catch (MessagingException e) { logger.error(e.getMessage(), e); fail(e.getMessage()); } } }
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);//from w ww .java2 s. co 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.robin.utilities.Utilities.java
/** * A utility that waits for a gmail mailbox to receive a new message with * according to a given SearchTerm. Only "Not seen" messages are searched, * and all match is set as SEEN, but just the first occurrence of the * matching message is returned./*w ww .jav a 2 s.co m*/ * @param username the mailbox owner's user name (no @gmail.com required). * @param pass the user password protecting this mailbox * @param st the SearchTerm built to filter messages * @param timeoutMessage the message to show when no such mail found within * timeout * @param timeout The maximum amount of time to wait in milliseconds. * @return a last from the new messages thats match the st conditions */ public EMail waitForMailWithSearchTerm(final String username, final String pass, final SearchTerm st, final String timeoutMessage, final long timeout) { String host = "imap.gmail.com"; final long retryTime = 1000; Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); props.put("mail.imaps.ssl.trust", "*"); EMail email = null; Session session = Session.getDefaultInstance(props, null); try { Store store = session.getStore("imaps"); store.connect(host, username, pass); Folder inbox = store.getFolder("Inbox"); inbox.open(Folder.READ_WRITE); FluentWait<Folder> waitForMail = new FluentWait<Folder>(inbox) .withTimeout(timeout, TimeUnit.MILLISECONDS).pollingEvery(retryTime, TimeUnit.MILLISECONDS) .withMessage(timeoutMessage); email = waitForMail.until(new Function<Folder, EMail>() { @Override public EMail apply(final Folder inbox) { EMail email = null; FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false); SearchTerm sst = new AndTerm(ft, st); try { inbox.getMessageCount(); Message[] messages = inbox.search(sst); for (Message message : messages) { message.setFlag(Flag.SEEN, true); } if (messages.length > 0) { return new EMail(messages[0]); } } catch (MessagingException e) { Assert.fail(e.getMessage()); } return email; } }); inbox.close(false); store.close(); } catch (MessagingException e) { Assert.fail(e.getMessage()); } return email; }
From source file:pt.lsts.neptus.comm.iridium.RockBlockIridiumMessenger.java
@Override public Collection<IridiumMessage> pollMessages(Date timeSince) throws Exception { if (askGmailPassword || gmailPassword == null || gmailUsername == null) { Pair<String, String> credentials = GuiUtils.askCredentials(ConfigFetch.getSuperParentFrame(), "Enter Gmail Credentials", getGmailUsername(), getGmailPassword()); if (credentials == null) return null; setGmailUsername(credentials.first()); setGmailPassword(credentials.second()); PluginUtils.saveProperties("conf/rockblock.props", this); askGmailPassword = false;//from ww w. j a v a 2 s . c om } Properties props = new Properties(); props.put("mail.store.protocol", "imaps"); ArrayList<IridiumMessage> messages = new ArrayList<>(); try { Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("imap.gmail.com", getGmailUsername(), getGmailPassword()); Folder inbox = store.getFolder("Inbox"); inbox.open(Folder.READ_ONLY); int numMsgs = inbox.getMessageCount(); for (int i = numMsgs; i > 0; i--) { Message m = inbox.getMessage(i); if (m.getReceivedDate().before(timeSince)) { break; } else { MimeMultipart mime = (MimeMultipart) m.getContent(); for (int j = 0; j < mime.getCount(); j++) { BodyPart p = mime.getBodyPart(j); Matcher matcher = pattern.matcher(p.getContentType()); if (matcher.matches()) { InputStream stream = (InputStream) p.getContent(); byte[] data = IOUtils.toByteArray(stream); IridiumMessage msg = process(data, matcher.group(1)); if (msg != null) messages.add(msg); } } } } } catch (NoSuchProviderException ex) { ex.printStackTrace(); System.exit(1); } catch (MessagingException ex) { ex.printStackTrace(); System.exit(2); } return messages; }