List of usage examples for javax.mail Folder open
public abstract void open(int mode) throws MessagingException;
From source file:org.wso2.esb.integration.common.utils.MailToTransportUtil.java
/** * Check a particular email has received to a given email folder by email subject. * * @param emailSubject - Email emailSubject to find email is in inbox or not * @return - found the email or not//from w w w .j av a 2 s . c o m * @throws ESBMailTransportIntegrationTestException - Is thrown if an error occurred while reading the emails */ public static boolean isMailReceivedBySubject(String emailSubject, String folder) throws ESBMailTransportIntegrationTestException { boolean emailReceived = false; Folder mailFolder; Store store = getConnection(); try { mailFolder = store.getFolder(folder); mailFolder.open(Folder.READ_WRITE); SearchTerm searchTerm = new AndTerm(new SubjectTerm(emailSubject), new BodyTerm(emailSubject)); Message[] messages = mailFolder.search(searchTerm); for (Message message : messages) { if (message.getSubject().contains(emailSubject)) { log.info("Found the email emailSubject : " + emailSubject); emailReceived = true; break; } } return emailReceived; } catch (MessagingException ex) { log.error("Error when getting mail count ", ex); throw new ESBMailTransportIntegrationTestException("Error when getting mail count ", ex); } finally { if (store != null) { try { store.close(); } catch (MessagingException e) { log.warn("Error when closing the store ", e); } } } }
From source file:org.wso2.esb.integration.common.utils.MailToTransportUtil.java
/** * Delete all unread emails from inbox/* ww w . j a v a 2 s.c o m*/ * * @throws ESBMailTransportIntegrationTestException - Is thrown if an error when deleting the emails */ public static void deleteAllUnreadEmailsFromGmail() throws ESBMailTransportIntegrationTestException { Folder inbox = null; Store store = getConnection(); try { inbox = store.getFolder(EMAIL_INBOX); inbox.open(Folder.READ_WRITE); Message[] messages = inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); for (Message message : messages) { message.setFlag(Flags.Flag.DELETED, true); log.info("Deleted email Subject : " + message.getSubject()); } } catch (MessagingException e) { log.error("Error when deleting emails from inbox", e); throw new ESBMailTransportIntegrationTestException("Error when deleting emails from inbox ", e); } finally { if (inbox != null) { try { inbox.close(true); } catch (MessagingException e) { log.warn("Error when closing the email folder : ", e); } } if (store != null) { try { store.close(); } catch (MessagingException e) { log.warn("Error when closing the email store : ", e); } } } }
From source file:org.jevis.emaildatasource.EMailManager.java
/** * Get list of messages//from w w w . j a v a 2s .c o m * * @param folder * @param conn * * @return List of Message */ private static List<Message> getMessageList(Folder folder, EMailChannelParameters chanParam) { List<Message> messageList = null; SearchTerm term = chanParam.getSearchTerms(); try { folder.open(Folder.READ_ONLY); } catch (MessagingException ex) { Logger.getLogger(EMailManager.class.getName()).log(Level.SEVERE, "EMail folder is not available to read.", ex); } Message[] msgs = null; Logger.getLogger(EMailManager.class.getName()).log(Level.INFO, "Folder is open: {0}", folder.isOpen()); if (chanParam.getProtocol().equalsIgnoreCase(EMailConstants.Protocol.IMAP)) { try { msgs = folder.search(term); } catch (MessagingException ex) { Logger.getLogger(EMailManager.class.getName()).log(Level.SEVERE, "Unable to search messages", ex); } } else if (chanParam.getProtocol().equalsIgnoreCase(EMailConstants.Protocol.POP3)) { try { // int[] msgnums = new int[1000]; // Message[] messages = folder.getMessages(msgnums); Message[] messages = folder.getMessages(); messages = filterPOP3ByDate(messages, chanParam.getLastReadout()); msgs = folder.search(term, messages); } catch (MessagingException ex) { Logger.getLogger(EMailManager.class.getName()).log(Level.SEVERE, "POP3: failed to receive messages from a folder.", ex); } } else { Logger.getLogger(EMailManager.class.getName()).log(Level.SEVERE, "Unable to search messages"); } messageList = Arrays.asList(msgs); Logger.getLogger(EMailManager.class.getName()).log(Level.INFO, "Messages found: {0}", messageList.size()); return messageList; }
From source file:com.email.ReceiveEmail.java
/** * This account fetches emails from a specified account and marks the emails * as seen, only touches the email account does not delete or move any * information./*from w w w . j a v a 2s. c o m*/ * * @param account SystemEmailModel */ public static void fetchEmail(SystemEmailModel account) { Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account); Properties properties = EmailProperties.setEmailInProperties(account); try { Session session = Session.getInstance(properties, auth); Store store = session.getStore(); store.connect(account.getIncomingURL(), account.getIncomingPort(), account.getUsername(), account.getPassword()); Folder fetchFolder = store.getFolder(account.getIncomingFolder()); if (account.getIncomingFolder().trim().equals("")) { fetchFolder = store.getFolder("INBOX"); } if (fetchFolder.exists()) { fetchFolder.open(Folder.READ_WRITE); Message[] msgs = fetchFolder.getMessages(); // USE THIS FOR UNSEEN MAIL TO SEEN MAIL //Flags seen = new Flags(Flags.Flag.SEEN); //FlagTerm unseenFlagTerm = new FlagTerm(seen, false); //Message[] msgs = fetchFolder.search(unseenFlagTerm); //fetchFolder.setFlags(msgs, seen, true); if (msgs.length > 0) { List<String> messageList = new ArrayList<>(); for (Message msg : msgs) { boolean notDuplicate = true; String headerText = Arrays.toString(msg.getHeader("Message-ID")); for (String header : messageList) { if (header.equals(headerText)) { notDuplicate = false; break; } } if (notDuplicate) { //Add to header to stop duplicates messageList.add(headerText); attachmentCount = 1; attachmentList = new ArrayList<>(); //Setup Email For dbo.Email EmailMessageModel eml = new EmailMessageModel(); String emailTime = String.valueOf(new Date().getTime()); eml.setSection(account.getSection()); eml = saveEnvelope(msg, msg, eml); eml.setId(EMail.InsertEmail(eml)); //After Email has been inserted Gather Attachments saveAttachments(msg, msg, eml); //Create Email Body eml = EmailBodyToPDF.createEmailBodyIn(eml, emailTime, attachmentList); //Insert Email Body As Attachment (so it shows up in attachment table during Docketing) EmailAttachment.insertEmailAttachment(eml.getId(), eml.getEmailBodyFileName()); //Flag email As ready to file so it is available in the docket tab of SERB3.0 eml.setReadyToFile(1); EMail.setEmailReadyToFile(eml); } if (deleteEmailEnabled) { // Will Delete message from server // Un Comment line below to run msg.setFlag(Flags.Flag.DELETED, true); } } } fetchFolder.close(true); store.close(); } } catch (MessagingException ex) { if (ex != null) { System.out.println("Unable to connect to email Server for: " + account.getEmailAddress() + "\nPlease ensure you are connected to the network and" + " try again."); } ExceptionHandler.Handle(ex); } }
From source file:org.wso2.es.ui.integration.util.ESUtil.java
/** * To check if a e-mail exists with a given subject * * @param smtpPropertyFile smtp property file path * @param password password/*from ww w . j a v a2 s. c om*/ * @param email email address * @param subject email subject * @return if the mail exist * @throws java.io.IOException * @throws MessagingException * @throws InterruptedException */ public static String readEmail(String smtpPropertyFile, String password, String email, String subject) throws MessagingException, InterruptedException, IOException { Properties props = new Properties(); String message = null; Folder inbox = null; Store store = null; FileInputStream inputStream = null; try { inputStream = new FileInputStream(new File(smtpPropertyFile)); props.load(inputStream); Session session = Session.getDefaultInstance(props, null); store = session.getStore(IMAPS); store.connect(SMTP_GMAIL_COM, email, password); inbox = store.getFolder(INBOX); inbox.open(Folder.READ_ONLY); message = getMailWithSubject(inbox, subject); } catch (MessagingException e) { LOG.error(getErrorMessage(email), e); throw e; } catch (InterruptedException e) { LOG.error(getErrorMessage(email), e); throw e; } catch (FileNotFoundException e) { LOG.error(getErrorMessage(email), e); throw e; } catch (IOException e) { LOG.error(getErrorMessage(email), e); throw e; } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { LOG.error("Input stream closing failed"); } } if (inbox != null) { try { inbox.close(true); } catch (MessagingException e) { LOG.error("Inbox closing failed"); } } if (store != null) { try { store.close(); } catch (MessagingException e) { LOG.error("Message store closing failed"); } } } return message; }
From source file:edu.ku.brc.helpers.EMailHelper.java
/** * Retrieves all the message from the INBOX. * @param store the store to retrieve them from * @param msgList the list to add them to * @return true if successful, false if their was an exception *//* w w w. java 2s.c om*/ public static boolean getMessagesFromInbox(final Store store, final java.util.List<javax.mail.Message> msgList) { try { Folder inbox = store.getDefaultFolder().getFolder("Inbox"); //$NON-NLS-1$ inbox.open(Folder.READ_ONLY); javax.mail.Message[] messages = inbox.getMessages(); Collections.addAll(msgList, messages); MailBoxInfo mbx = instance.new MailBoxInfo(store, inbox); instance.mailBoxCache.add(mbx); return true; } catch (MessagingException mex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex); instance.lastErrorMsg = mex.toString(); } return false; }
From source file:dao.FetchEmailDAO.java
/** * * @return//from ww w . j a v a 2 s . c o m */ public Message[] fetchEmail() { Properties props = new Properties(); props.setProperty("mail.store.protocol", "imaps"); //store inbox emails as Message object, store all into Message[] array. Message[] msgArr = null; try { Session session = Session.getInstance(props, null); Store store = session.getStore(); store.connect("imap-mail.outlook.com", "joshymantou@outlook.com", "mcgrady11"); Folder inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_ONLY); msgArr = inbox.getMessages(); //System.out.println(msgArr.length); /*for (int i = 0; i < msgArr.length; i++) { Message msg = msgArr[i]; Address[] in = msg.getFrom(); for (Address address : in) { System.out.println("FROM:" + address.toString()); } Multipart mp = (Multipart) msg.getContent(); BodyPart bp = mp.getBodyPart(0); /* System.out.println("SENT DATE:" + msg.getSentDate()); System.out.println("SUBJECT:" + msg.getSubject()); System.out.println("CONTENT:" + bp.getContent()); }*/ ArrayUtils.reverse(msgArr); return msgArr; } catch (Exception mex) { mex.printStackTrace(); } return msgArr; }
From source file:com.treesbearfruit.icloudnotes.NotesSaver.java
private void save(Store store, String wheretobackup, String f) throws MessagingException, IOException { System.out.println("opening folder " + f); Folder folder = store.getFolder(f); folder.open(Folder.READ_ONLY); FileUtils.forceMkdir(new File(wheretobackup)); // Get directory Message message[] = folder.getMessages(); for (int i = 0, n = message.length; i < n; i++) { // String from = (message[i].getFrom()[0]).toString(); String subj = (message[i].getSubject()).toString(); String nota = (message[i].getContent()).toString(); // System.out.println("from: " + from); System.out.println("saving: " + subj); // BACKUP NOTE generals.writeFile(wheretobackup + "/" + generals.makeFilename(subj).trim() + ".html", nota, message[i].getSentDate()); }//from w ww . j a v a2 s . c om folder.close(false); }
From source file:ru.codemine.ccms.mail.EmailAttachmentExtractor.java
public void saveAllAttachment() { String protocol = ssl ? "imaps" : "imap"; Properties props = new Properties(); props.put("mail.store.protocol", protocol); try {//from ww w. j a va 2 s .com Session session = Session.getInstance(props); Store store = session.getStore(); store.connect(host, port, username, password); Folder inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_WRITE); for (Message msg : inbox.getMessages()) { if (!msg.isSet(Flags.Flag.SEEN)) { String fileNamePrefix = settingsService.getStorageEmailPath() + "msg-" + msg.getMessageNumber(); Multipart multipart = (Multipart) msg.getContent(); for (int i = 0; i < multipart.getCount(); i++) { BodyPart bodyPart = multipart.getBodyPart(i); if (Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) && StringUtils.isNotEmpty(bodyPart.getFileName())) { MimeBodyPart mimimi = (MimeBodyPart) bodyPart; // =(^.^)= mimimi.saveFile(fileNamePrefix + MimeUtility.decodeText(bodyPart.getFileName())); msg.setFlag(Flags.Flag.SEEN, true); } } } } } catch (IOException | MessagingException e) { log.error("? ? ?, : " + e.getMessage()); } }
From source file:com.trivago.mail.pigeon.mail.MailFacade.java
public void readBounceAccount() throws MessagingException { Session session = Session.getDefaultInstance(Settings.create().getConfiguration().getProperties("mail.*")); Store store = session.getStore("pop3"); store.connect();// ww w .j a v a 2s .c om // Get folder Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_ONLY); if (folder.hasNewMessages()) { // Get directory Message message[] = folder.getMessages(); BounceFacade bounceFacade = new BounceFacade(); for (Message msg : message) { boolean isBounce = bounceFacade.processBounce(msg); if (isBounce) { msg.setFlag(Flags.Flag.SEEN, true); msg.saveChanges(); } } } }