List of usage examples for javax.mail Folder open
public abstract void open(int mode) throws MessagingException;
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 ava 2s . 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.xwiki.contrib.mail.internal.AbstractMailStore.java
/** * {@inheritDoc}// ww w. j a v a 2 s. c o m * * @see org.xwiki.contrib.mail.IMailReader#readFromStore(java.lang.String) */ @Override public List<Message> read(String folder, boolean onlyUnred, int max) throws MessagingException { Store store = getJavamailStore(); store.connect(); Folder mailFolder = store.getDefaultFolder(); if (StringUtils.isNotEmpty(folder)) { mailFolder = mailFolder.getFolder(folder); } mailFolder.open(Folder.READ_WRITE); Message[] msgsArray = mailFolder.getMessages(); if (max > 0 && msgsArray.length > max) { msgsArray = (Message[]) ArrayUtils.subarray(msgsArray, 0, max); } List<Message> messages = new ArrayList<Message>(Arrays.asList(msgsArray)); mailFolder.close(false); store.close(); return messages; }
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;/* w w w .j a v a2 s . co m*/ } 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; }
From source file:org.xwiki.contrib.mail.internal.AbstractMailStore.java
/** * @param folder/*from w ww. j av a 2 s .c om*/ * @param message * @throws MessagingException */ public void write(String folder, Message message) throws MessagingException { // getLogger().info("Delivering " + message + " to " + this.location + " / " + folder); final Store store = getJavamailStore(true); store.connect(); final Folder mailFolder = store.getDefaultFolder().getFolder(folder); if (!mailFolder.exists()) { mailFolder.create(Folder.HOLDS_MESSAGES); } mailFolder.open(Folder.READ_WRITE); // If message is already archived, do nothing final Message existingMessage = read(folder, message.getHeader("Message-ID")[0]); if (existingMessage == null) { // The Store Provider may add some headers to the message to store, but IMAPMessage are read-only // So we clone the message before storing it final MimeMessage cloned = cloneEmail(message); mailFolder.appendMessages(new Message[] { cloned }); } mailFolder.close(true); store.close(); }
From source file:ru.retbansk.utils.scheduled.impl.ReadEmailAndConvertToXmlSpringImpl.java
/** * Loads email properties, reads email messages, * converts their multipart bodies into string, * send error emails if message doesn't contain valid report and at last returns a reversed Set of the Valid Reports * <p><b> deletes messages//ww w. ja va 2 s. co m * @see #readEmail() * @see #convertToXml(HashSet) * @see ru.retbansk.utils.scheduled.ReplyManager * @return HashSet<DayReport> of the Valid Day Reports */ @Override public HashSet<DayReport> readEmail() throws Exception { Properties prop = loadProperties(); String host = prop.getProperty("host"); String user = prop.getProperty("user"); String password = prop.getProperty("password"); path = prop.getProperty("path"); // Get system properties Properties properties = System.getProperties(); // Get the default Session object. Session session = Session.getDefaultInstance(properties); // Get a Store object that implements the specified protocol. Store store = session.getStore("pop3"); // Connect to the current host using the specified username and // password. store.connect(host, user, password); // Create a Folder object corresponding to the given name. Folder folder = store.getFolder("inbox"); // Open the Folder. folder.open(Folder.READ_WRITE); HashSet<DayReport> dayReportSet = new HashSet<DayReport>(); try { // Getting messages from the folder Message[] message = folder.getMessages(); // Reversing the order in the array with the use of Set to make the last one final Collections.reverse(Arrays.asList(message)); // Reading messages. String body; for (int i = 0; i < message.length; i++) { DayReport dayReport = null; dayReport = new DayReport(); dayReport.setPersonId(((InternetAddress) message[i].getFrom()[0]).getAddress()); Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+3")); calendar.setTime(message[i].getSentDate()); dayReport.setCalendar(calendar); dayReport.setSubject(message[i].getSubject()); List<TaskReport> reportList = null; //Release the string from email message body body = ""; Object content = message[i].getContent(); if (content instanceof java.lang.String) { body = (String) content; } else if (content instanceof Multipart) { Multipart mp = (Multipart) content; for (int j = 0; j < mp.getCount(); j++) { Part part = mp.getBodyPart(j); String disposition = part.getDisposition(); if (disposition == null) { MimeBodyPart mbp = (MimeBodyPart) part; if (mbp.isMimeType("text/plain")) { body += (String) mbp.getContent(); } } else if ((disposition != null) && (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE))) { MimeBodyPart mbp = (MimeBodyPart) part; if (mbp.isMimeType("text/plain")) { body += (String) mbp.getContent(); } } } } //Put the string (body of email message) and get list of valid reports else send error reportList = new ArrayList<TaskReport>(); reportList = giveValidReports(body, message[i].getSentDate()); //Check for valid day report. To be valid it should have size of reportList > 0. if (reportList.size() > 0) { // adding valid ones to Set dayReport.setReportList(reportList); dayReportSet.add(dayReport); } else { // This message doesn't have valid reports. Sending an error reply. logger.info("Invalid Day Report detected. Sending an error reply"); ReplyManager man = new ReplyManagerSimpleImpl(); man.sendError(dayReport); } // Delete message message[i].setFlag(Flags.Flag.DELETED, true); } } finally { // true tells the mail server to expunge deleted messages. folder.close(true); store.close(); } return dayReportSet; }
From source file:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java
protected void deleteMailsFromUserMailbox(final Properties props, final String folderName, final int start, final int deleteCount, final String user, final String password) throws MessagingException { final Store store = Session.getInstance(props).getStore(); store.connect(user, password);//from w ww . j av a2 s. co m checkStoreForTestConnection(store); final Folder f = store.getFolder(folderName); f.open(Folder.READ_WRITE); final int msgCount = f.getMessageCount(); final Message[] m = deleteCount == -1 ? f.getMessages() : f.getMessages(start, Math.min(msgCount, deleteCount + start - 1)); int d = 0; for (final Message message : m) { message.setFlag(Flag.DELETED, true); logger.info("Delete msgnum: {} with sid {}", message.getMessageNumber(), message.getSubject()); d++; } f.close(true); logger.info("Deleted " + d + " messages"); store.close(); }
From source file:com.aquest.emailmarketing.web.service.BouncedEmailService.java
/** * Process bounces./*from www . j a v a 2s .c om*/ * * @param protocol the protocol * @param host the host * @param port the port * @param userName the user name * @param password the password */ public void processBounces(String protocol, String host, String port, String userName, String password) { Properties properties = getServerProperties(protocol, host, port); Session session = Session.getDefaultInstance(properties); List<BounceCode> bounceCodes = bounceCodeService.getAllBounceCodes(); try { // connects to the message store Store store = session.getStore(protocol); System.out.println(userName); System.out.println(password); System.out.println(userName.length()); System.out.println(password.length()); //store.connect(userName, password); //TODO: ispraviti username i password da idu iz poziva a ne hardcoded store.connect("bojan.dimic@aquest-solutions.com", "bg181076"); // 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++) { BouncedEmail bouncedEmail = new BouncedEmail(); Message msg = messages[i]; Address[] fromAddress = msg.getFrom(); String from = fromAddress[0].toString(); String failedAddress = ""; Enumeration<?> headers = messages[i].getAllHeaders(); while (headers.hasMoreElements()) { Header h = (Header) headers.nextElement(); //System.out.println(h.getName() + ":" + h.getValue()); //System.out.println(""); String mID = h.getName(); if (mID.contains("X-Failed-Recipients")) { failedAddress = h.getValue(); } } 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(); } } String bounceReason = "Unknown reason"; for (BounceCode bounceCode : bounceCodes) { if (messageContent.contains(bounceCode.getCode())) { bounceReason = bounceCode.getExplanation(); } } // if(messageContent.contains(" 550 ") || messageContent.contains(" 550-")) {bounceReason="Users mailbox was unavailable (such as not found)";} // if(messageContent.contains(" 554 ") || messageContent.contains(" 554-")) {bounceReason="The transaction failed for some unstated reason.";} // // // enhanced bounce codes // if(messageContent.contains("5.0.0")) {bounceReason="Unknown issue";} // if(messageContent.contains("5.1.0")) {bounceReason="Other address status";} // if(messageContent.contains("5.1.1")) {bounceReason="Bad destination mailbox address";} // if(messageContent.contains("5.1.2")) {bounceReason="Bad destination system address";} // if(messageContent.contains("5.1.3")) {bounceReason="Bad destination mailbox address syntax";} // if(messageContent.contains("5.1.4")) {bounceReason="Destination mailbox address ambiguous";} // if(messageContent.contains("5.1.5")) {bounceReason="Destination mailbox address valid";} // if(messageContent.contains("5.1.6")) {bounceReason="Mailbox has moved";} // if(messageContent.contains("5.7.1")) {bounceReason="Delivery not authorized, message refused";} // 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 X-Failed-Recipients:" + failedAddress); System.out.println("\t Content Type:" + contentType); System.out.println("\t Bounce reason:" + bounceReason); //System.out.println("\t Message: " + messageContent); bouncedEmail.setEmail_address(failedAddress); bouncedEmail.setBounce_reason(bounceReason); //Date date = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH); SimpleDateFormat sqlFormat = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH); //String strDate = date.toString(); System.out.println(sentDate); Date dt = null; //Date nd = null; try { dt = formatter.parse(sentDate); //nd = sqlFormat.parse(dt.toString()); } catch (ParseException e) { e.printStackTrace(); } System.out.println("Date " + dt.toString()); //System.out.println("Date " + nd.toString()); System.out.println(new Timestamp(new Date().getTime())); bouncedEmail.setSend_date(dt); bouncedEmailDao.saveOrUpdate(bouncedEmail); } // disconnect folderInbox.close(false); store.close(); } catch (NoSuchProviderException ex) { System.out.println("No provider for protocol: " + protocol); ex.printStackTrace(); } catch (MessagingException ex) { System.out.println("Could not connect to the message store"); ex.printStackTrace(); } }
From source file:com.jaeksoft.searchlib.crawler.mailbox.crawler.MailboxAbstractCrawler.java
protected void checkFolder(Folder folder, PrintWriter pw) throws MessagingException, IOException, SearchLibException { if (folder == null) return;//from w ww .j a v a 2 s . c o m if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0) { folder.open(Folder.READ_ONLY); try { pw.print("Folder "); pw.print(folder.getName()); pw.print(": "); pw.print(folder.getMessageCount()); pw.println(" msgs(s)."); } finally { folder.close(false); } } if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) { Folder[] folders = folder.list(); if (folders != null) for (Folder f : folders) checkFolder(f, pw); } }
From source file:edu.stanford.muse.email.MboxEmailStore.java
public Folder openFolderWithoutCount(Store s, String fname) throws MessagingException { if (fname == null) fname = "INBOX"; // ignore the store coming in, we need a new session and store // for each folder Session session = Session.getInstance(mstorProps, null); session.setDebug(DEBUG);//from w w w .j a va 2 s .co m // Get a Store object Store store = session.getStore(new URLName("mstor:" + fname)); store.connect(); //This is the root folder in the namespace provided //see http://docs.oracle.com/javaee/5/api/javax/mail/Store.html#getDefaultFolder%28%29 Folder folder = store.getDefaultFolder(); if (folder == null) throw new RuntimeException("Invalid folder: " + fname); log.info("Opening folder " + Util.blurPath(fname) + " in r/o mode..."); try { folder.open(Folder.READ_ONLY); } catch (MessagingException me) { folder = null; } return folder; }
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;/*from w w w. j a v a 2s . com*/ Folder folder = null; 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()); } } }