List of usage examples for javax.mail Folder getMessages
public synchronized Message[] getMessages() throws MessagingException
From source file:org.wso2.esb.integration.common.utils.servers.GreenMailServer.java
/** * Delete all emails in the inbox.//from w w w . j a v a 2 s. co m * * @param protocol protocol used to connect to the server * @throws MessagingException if we're unable to connect to the store */ public static void deleteAllEmails(String protocol, GreenMailUser user) throws MessagingException { Folder inbox = null; Store store = getConnection(user, protocol); try { inbox = store.getFolder(EMAIL_INBOX); inbox.open(Folder.READ_WRITE); Message[] messages = inbox.getMessages(); for (Message message : messages) { message.setFlag(Flags.Flag.DELETED, true); log.info("Deleted email Subject : " + message.getSubject()); } } finally { if (inbox != null) { inbox.close(true); } if (store != null) { store.close(); } } }
From source file:org.wso2.carbon.registry.es.utils.EmailUtil.java
/** * This method delete all the sent mails. Can be used after a particular test class * * @throws MessagingException/*from w w w .j av a 2 s. c om*/ * @throws IOException */ public static void deleteSentMails() throws MessagingException, IOException { Properties props = new Properties(); props.load(new FileInputStream(new File(TestConfigurationProvider.getResourceLocation("GREG") + File.separator + "axis2" + File.separator + "smtp.properties"))); Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("smtp.gmail.com", emailAddress, java.nio.CharBuffer.wrap(emailPassword).toString()); Folder sentMail = store.getFolder("[Gmail]/Sent Mail"); sentMail.open(Folder.READ_WRITE); Message[] messages = sentMail.getMessages(); Flags deleted = new Flags(Flags.Flag.DELETED); sentMail.setFlags(messages, deleted, true); sentMail.close(true); store.close(); }
From source file:org.apache.hupa.server.preferences.InImapUserPreferencesStorage.java
/** * Opens the IMAP folder and read messages until it founds the magic subject, * then gets the attachment which contains the data and return the serialized object stored. *//* w w w . ja v a2 s . c om*/ protected static Object readUserPreferencesFromIMAP(Log logger, User user, IMAPStore iStore, String folderName, String magicType) throws MessagingException, IOException, ClassNotFoundException { Folder folder = iStore.getFolder(folderName); if (folder.exists()) { if (!folder.isOpen()) { folder.open(Folder.READ_WRITE); } Message message = null; Message[] msgs = folder.getMessages(); for (Message msg : msgs) { if (magicType.equals(msg.getSubject())) { message = msg; break; } } if (message != null) { Object con = message.getContent(); if (con instanceof Multipart) { Multipart mp = (Multipart) con; for (int i = 0; i < mp.getCount(); i++) { BodyPart part = mp.getBodyPart(i); if (part.getContentType().toLowerCase().startsWith(HUPA_DATA_MIME_TYPE)) { ObjectInputStream ois = new ObjectInputStream(part.getInputStream()); Object o = ois.readObject(); ois.close(); logger.info("Returning user preferences of type " + magicType + " from imap folder + " + folderName + " for user " + user); return o; } } } } } return null; }
From source file:org.wso2.carbon.registry.es.utils.EmailUtil.java
/** * This method read verification e-mail from Gmail inbox and returns the verification URL. * * @return verification redirection URL. * @throws Exception//from w w w . j a v a 2 s .c om */ public static String readGmailInboxForVerification() throws Exception { boolean isEmailVerified = false; long waitTime = 10000; String pointBrowserURL = ""; Properties props = new Properties(); props.load(new FileInputStream(new File(TestConfigurationProvider.getResourceLocation("GREG") + File.separator + "axis2" + File.separator + "smtp.properties"))); Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("smtp.gmail.com", emailAddress, java.nio.CharBuffer.wrap(emailPassword).toString()); Folder inbox = store.getFolder("inbox"); inbox.open(Folder.READ_WRITE); Thread.sleep(waitTime); long startTime = System.currentTimeMillis(); long endTime = 0; int count = 1; while (endTime - startTime < 180000 && !isEmailVerified) { Message[] messages = inbox.getMessages(); for (Message message : messages) { if (!message.isExpunged()) { try { log.info("Mail Subject:- " + message.getSubject()); if (message.getSubject().contains("EmailVerification")) { pointBrowserURL = getBodyFromMessage(message); isEmailVerified = true; } // Optional : deleting the mail message.setFlag(Flags.Flag.DELETED, true); } catch (MessageRemovedException e) { log.error("Could not read the message subject. Message is removed from inbox"); } } } endTime = System.currentTimeMillis(); Thread.sleep(waitTime); endTime += count * waitTime; count++; } inbox.close(true); store.close(); return pointBrowserURL; }
From source file:org.wso2.carbon.registry.es.utils.EmailUtil.java
/** * This method read e-mails from Gmail inbox and find whether the notification of particular type is found. * * @param notificationType Notification types supported by publisher and store. * @return whether email is found for particular type. * @throws Exception//from w w w. j av a 2 s . c o m */ public static boolean readGmailInboxForNotification(String notificationType) throws Exception { boolean isNotificationMailAvailable = false; long waitTime = 10000; Properties props = new Properties(); props.load(new FileInputStream(new File(TestConfigurationProvider.getResourceLocation("GREG") + File.separator + "axis2" + File.separator + "smtp.properties"))); Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("smtp.gmail.com", emailAddress, java.nio.CharBuffer.wrap(emailPassword).toString()); Folder inbox = store.getFolder("inbox"); inbox.open(Folder.READ_WRITE); Thread.sleep(waitTime); long startTime = System.currentTimeMillis(); long endTime = 0; int count = 1; while (endTime - startTime < 180000 && !isNotificationMailAvailable) { Message[] messages = inbox.getMessages(); for (Message message : messages) { if (!message.isExpunged()) { try { log.info("Mail Subject:- " + message.getSubject()); if (message.getSubject().contains(notificationType)) { isNotificationMailAvailable = true; } // Optional : deleting the mail message.setFlag(Flags.Flag.DELETED, true); } catch (MessageRemovedException e) { log.error("Could not read the message subject. Message is removed from inbox"); } } } endTime = System.currentTimeMillis(); Thread.sleep(waitTime); endTime += count * waitTime; count++; } inbox.close(true); store.close(); return isNotificationMailAvailable; }
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 a2s.c om * * @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: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 *///from w w w. j ava 2 s .c o m 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 w w w . j a v a2 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: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 {// www.j av a2s . c o m 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.ieprofile.helper.gmail.OAuth2Authenticator.java
/** * Connects and authenticates to an IMAP server with OAuth2. You must have * called {@code initialize}.//from ww w.j a va2 s.co m * * @param host Hostname of the imap server, for example {@code * imap.googlemail.com}. * @param port Port of the imap server, for example 993. * @param userEmail Email address of the user to authenticate, for example * {@code oauth@gmail.com}. * @param oauthToken The user's OAuth token. * @param debug Whether to enable debug logging on the IMAP connection. * * @return An authenticated IMAPStore that can be used for IMAP operations. */ public List<MessageBean> connectToImap(String host, int port, String userEmail, String oauthToken, boolean debug) throws Exception { Properties props = new Properties(); props.put("mail.imaps.sasl.enable", "true"); props.put("mail.imaps.sasl.mechanisms", "XOAUTH2"); props.put(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP, oauthToken); Session session = Session.getInstance(props); session.setDebug(debug); final URLName unusedUrlName = null; IMAPSSLStore store = new IMAPSSLStore(session, unusedUrlName); final String emptyPassword = ""; store.connect(host, port, userEmail, emptyPassword); Folder inbox = store.getFolder("Inbox"); inbox.open(Folder.READ_WRITE); Message messages[] = inbox.getMessages(); int messageCount = inbox.getMessageCount(); List<String> attachments = new ArrayList<String>(); LinkedList<MessageBean> listMessages = emailListener.sendMessage(messages, attachments); emailRepo.addAllMessages(listMessages); emailListener.folder = inbox; emailListener.started = false; emailListener.start(); //ArrayList<String> attachments = new ArrayList<String>(); //LinkedList<MessageBean> listMessages = getPart(messages, attachments); //store.close(); return emailRepo.getMessages(); }