public void getEmail() throws MessagingException, IOException { Session session = Session.getDefaultInstance(System.getProperties(),null); Store store = null; store = session.getStore("imaps"); // store.connect(this.host, this.userName, this.password); // Get default folder Folder folder = store.getDefaultFolder(); folder.getMessages(); folder.getNewMessageCount(); Message m = folder.getMessage(0); m.getMessageNumber(); m.getAllRecipients(); m.getReceivedDate(); m.getFrom(); m.getSubject(); m.getReplyTo(); m.getContent(); m.getSize(); // Get any folder by name Folder[] folderList = folder.list(); }
/** * Close connection * <b>Note</b>Internal method * @throws MessagingException */ public void closeStoreConnection( boolean storeConnected ) throws MessagingException { if (storeConnected) { // the folder is empty when the message is not loaded from IMAP server, but from a file Folder imapFolder = message.getFolder(); if (imapFolder == null) { imapFolder = partOfImapFolder; // in case of nested package but still originating from IMAP server } if (imapFolder != null) { Store store = imapFolder.getStore(); if (store != null && store.isConnected()) { // closing store closes and its folders log.debug("Closing store (" + store.toString() + ") and associated folders"); store.close(); } } } }
private void prepareMailbox() throws Exception { // connect to mailbox Mailbox.clearAll(); JavaMailSender sender = new DefaultJavaMailSender(); Store store = sender.getSession().getStore("pop3"); store.connect("localhost", 25, "jones", "secret"); Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_WRITE); folder.expunge(); // inserts 5 new messages Message[] messages = new Message[5]; for (int i = 0; i < 5; i++) { messages[i] = new MimeMessage(sender.getSession()); messages[i].setHeader("Message-ID", "" + i); messages[i].setText("Message " + i); } folder.appendMessages(messages); folder.close(true); }
private static void initInbox() { try { System.out.println("Inbox initiating..."); Properties props = new Properties(); props.setProperty(MAIL_STORE_PROTOCOL_KEY, mailConfig.getProperty(MAIL_STORE_PROTOCOL_KEY)); // Used gmail with lesser secure authentication (https://www.google.com/settings/security/lesssecureapps) // For a full access I should implement OAuth2 for ArdulinkMail (https://java.net/projects/javamail/pages/OAuth2) Session session = Session.getInstance(props, null); Store store = session.getStore(); System.out.println(mailConfig.getProperty(MAIL_HOST_KEY) + " " + mailConfig.getProperty(MAIL_USER_KEY) + " " + mailConfig.getProperty(MAIL_PASSWORD_KEY)); store.connect(mailConfig.getProperty(MAIL_HOST_KEY), mailConfig.getProperty(MAIL_USER_KEY), mailConfig.getProperty(MAIL_PASSWORD_KEY)); // clearDefault(store.getDefaultFolder()); // With GMAIL it doesn't work since "all messages" cannot be cleared. clearMainFolder(store.getFolder("INBOX")); inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_WRITE); System.out.println("Inbox initiated"); } catch (Exception e) { throw new IllegalStateException("Error initiating inbox. Exiting..."); } }
/** * Reconnects if connection is closed. * <b>Note</b>Internal method * @return true if store re-connection is performed and this means that close should be closed after the work is done * @throws MessagingException */ public boolean reconnectStoreIfClosed() throws MessagingException { boolean storeReconnected = false; // the folder is empty when the message is not loaded from IMAP server, but from a file Folder imapFolder = message.getFolder(); if (imapFolder == null) { imapFolder = this.partOfImapFolder; } else { partOfImapFolder = imapFolder; // keep reference } if (imapFolder != null) { Store store = imapFolder.getStore(); if (store != null) { if (!store.isConnected()) { log.debug("Reconnecting store... "); store.connect(); storeReconnected = true; } // Open folder in read-only mode if (!imapFolder.isOpen()) { log.debug("Reopening folder " + imapFolder.getFullName() + " in order to get contents of mail message"); imapFolder.open(Folder.READ_ONLY); } } } return storeReconnected; }
/** * Check mail folder for an email using subject. * * @param emailSubject Email subject * @param folder mail folder to check for an email * @param protocol protocol used to connect to the server * @return whether mail received or not * @throws MessagingException if we're unable to connect to the store */ private static boolean isMailReceivedBySubject(String emailSubject, String folder, String protocol, GreenMailUser user) throws MessagingException { boolean emailReceived = false; Folder mailFolder; Store store = getConnection(user, protocol); 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 with Subject : " + emailSubject); emailReceived = true; break; } } } finally { if (store != null) { store.close(); } } return emailReceived; }
/** * Delete all emails in the inbox. * * @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(); } } }
/** * Check whether email received by reading the emails. * * @param protocol to connect to the store * @param user whose mail store should be connected * @param subject the subject of the mail to search * @return * @throws MessagingException when unable to connect to the store */ public static boolean isMailReceived(String protocol, GreenMailUser user, String subject) throws MessagingException { Store store = getConnection(user, protocol); Folder folder = store.getFolder(EMAIL_INBOX); folder.open(Folder.READ_ONLY); boolean isReceived = false; Message[] messages = folder.getMessages(); for (Message message : messages) { if (message.getSubject().contains(subject)) { log.info("Found the Email with Subject : " + subject); isReceived = true; break; } } return isReceived; }
/** * Asserts that a connection to the given mailbox is possible. * * @param protocol * The protocol. * @param isStartTls * True, if StartTLS ist possible. * @param host * The host. * @param port * The port. * @param login * The login. * @param password * The password. * @param mailbox * The mailbox. * @throws ConnectionException * Exception. * @throws MessagingException * Exception. */ private void assertConnection(String protocol, boolean isStartTls, String host, String port, String login, String password, String mailbox) throws ConnectionException, MessagingException { String propertiesProtocolPrefix = "mail." + protocol + "."; Properties properties = new Properties(); properties.putAll(System.getProperties()); properties.put(propertiesProtocolPrefix + "starttls.enable", isStartTls); Session session = Session.getInstance(properties); Store store = session.getStore(protocol); try { store.connect(host, NumberUtils.toInt(port, -1), login, password); Folder folder = store.getFolder(mailbox); if (!folder.exists()) { throw new FolderNotFoundException(); } } finally { store.close(); } }
private void prepareMailbox() throws Exception { // connect to mailbox Mailbox.clearAll(); JavaMailSender sender = new DefaultJavaMailSender(); Store store = sender.getSession().getStore("pop3"); store.connect("localhost", 25, "bill", "secret"); Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_WRITE); folder.expunge(); // inserts 1 new message Message[] messages = new Message[1]; messages[0] = new MimeMessage(sender.getSession()); messages[0].setSubject("TestSubject"); messages[0].setHeader("Message-ID", "0"); messages[0].setText("TestText"); folder.appendMessages(messages); folder.close(true); }
private void prepareMailbox() throws Exception { // connect to mailbox Mailbox.clearAll(); JavaMailSender sender = new DefaultJavaMailSender(); Store store = sender.getSession().getStore("imap"); store.connect("localhost", 25, "claus", "secret"); Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_WRITE); folder.expunge(); // inserts two new messages Message[] msg = new Message[2]; msg[0] = new MimeMessage(sender.getSession()); msg[0].setText("Message 1"); msg[0].setHeader("Message-ID", "0"); msg[0].setFlag(Flags.Flag.SEEN, false); msg[1] = new MimeMessage(sender.getSession()); msg[1].setText("Message 2"); msg[0].setHeader("Message-ID", "1"); msg[1].setFlag(Flags.Flag.SEEN, true); folder.appendMessages(msg); folder.close(true); }
private void prepareMailbox(String user, String type) throws Exception { // connect to mailbox JavaMailSender sender = new DefaultJavaMailSender(); Store store = sender.getSession().getStore(type); store.connect("localhost", 25, user, "secret"); Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_WRITE); folder.expunge(); InputStream is = getClass().getResourceAsStream("/SignedMailTestCaseHurz.elm"); Message hurzMsg = new MimeMessage(sender.getSession(), is); Message[] messages = new Message[] {hurzMsg}; // insert one signed message folder.appendMessages(messages); folder.close(true); }
private void prepareMailbox() throws Exception { // connect to mailbox Mailbox.clearAll(); JavaMailSender sender = new DefaultJavaMailSender(); Store store = sender.getSession().getStore("pop3"); store.connect("localhost", 25, "jones", "secret"); Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_WRITE); folder.expunge(); // inserts 5 new messages Message[] messages = new Message[5]; for (int i = 0; i < 5; i++) { messages[i] = new MimeMessage(sender.getSession()); messages[i].setText("Message " + i); messages[i].setHeader("Message-ID", "myuid-" + i); } folder.appendMessages(messages); folder.close(true); }
private void prepareMailbox() throws Exception { // connect to mailbox Mailbox.clearAll(); JavaMailSender sender = new DefaultJavaMailSender(); Store store = sender.getSession().getStore("imap"); store.connect("localhost", 25, "claus", "secret"); Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_WRITE); folder.expunge(); // inserts two messages with the SEEN flag Message[] msg = new Message[2]; msg[0] = new MimeMessage(sender.getSession()); msg[0].setText("Message 1"); msg[0].setHeader("Message-ID", "0"); msg[0].setFlag(Flags.Flag.SEEN, true); msg[1] = new MimeMessage(sender.getSession()); msg[1].setText("Message 2"); msg[0].setHeader("Message-ID", "1"); msg[1].setFlag(Flags.Flag.SEEN, true); folder.appendMessages(msg); folder.close(true); }
private void prepareMailbox() throws Exception { // connect to mailbox Mailbox.clearAll(); JavaMailSender sender = new DefaultJavaMailSender(); Store store = sender.getSession().getStore("pop3"); store.connect("localhost", 25, "jones", "secret"); Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_WRITE); folder.expunge(); // inserts 5 new messages Message[] messages = new Message[5]; for (int i = 0; i < 5; i++) { messages[i] = new MimeMessage(sender.getSession()); messages[i].setText("Message " + i); messages[i].setHeader("Message-ID", "" + i); } folder.appendMessages(messages); folder.close(true); }
public void checkInbox(int mode) throws MessagingException, IOException { if (mode == 0) { return; } boolean show = (mode & MailClient.SHOW_MESSAGES) > 0; boolean clear = (mode & MailClient.CLEAR_MESSAGES) > 0; String action = (show ? "Show" : "") + (show && clear ? " and " : "") + (clear ? "Clear" : ""); System.out.println(action + " INBOX for " + from); Store store = session.getStore(); store.connect(); Folder root = store.getDefaultFolder(); Folder inbox = root.getFolder("inbox"); inbox.open(Folder.READ_WRITE); Message[] msgs = inbox.getMessages(); if (msgs.length == 0 && show) { System.out.println("No messages in inbox"); } for (Message msg2 : msgs) { MimeMessage msg = (MimeMessage) msg2; if (show) { System.out.println(" From: " + msg.getFrom()[0]); System.out.println(" Subject: " + msg.getSubject()); System.out.println(" Content: " + msg.getContent()); } if (clear) { msg.setFlag(Flags.Flag.DELETED, true); } } inbox.close(true); store.close(); System.out.println(); }
public void checkInboxSave(int mode) throws MessagingException, IOException { Store store = session.getStore(); store.connect(); Folder root = store.getDefaultFolder(); Folder inbox = root.getFolder("inbox"); inbox.open(Folder.READ_WRITE); Message[] msgs = inbox.getMessages(); for (Message msg2 : msgs) { POP3Message msg = (POP3Message) msg2; Object object = msg.getContent(); if (object instanceof Multipart) { Multipart multipart = (Multipart) object; for (int i = 0, n = multipart.getCount(); i < n; i++) { MailClient.handlePart(multipart.getBodyPart(i)); } } System.out.println(" From: " + msg.getFrom()[0]); System.out.println(" Subject: " + msg.getSubject()); System.out.println(" Content: " + object); } inbox.close(true); store.close(); }
private Folder openFolder( cfSession _Session, Store popStore ) throws cfmRunTimeException { try{ Folder folder = popStore.getDefaultFolder(); Folder popFolder = folder.getFolder("INBOX"); popFolder.open( Folder.READ_WRITE ); return popFolder; }catch(Exception E){ throw newRunTimeException( E.getMessage() ); } }
private Store getStore(EmailAccount account) throws MessagingException { Store store = null; if (storeConnections == null) { // Log.d("rgai", "CREATING STORE CONTAINER"); storeConnections = new HashMap<EmailAccount, Store>(); } else { if (storeConnections.containsKey(account)) { store = storeConnections.get(account); // Log.d("rgai", "STORE EXISTS"); } } if (store == null || !store.isConnected()) { // Log.d("rgai", "CREATING STORE || reconnection store"); store = getStore(); storeConnections.put(account, store); } return store; }
/** * Handy method to do the try catch try of closing a mail store and folder. * @param mailStore * @param mailFolder */ private void closeStore(final Store mailStore, final Folder mailFolder) { try { if (mailFolder != null && mailFolder.isOpen()) { mailFolder.close(true); } } catch (final MessagingException e) { LogUtils.debugf(this, e, "Unable to close mail folder."); } finally { try { if (mailStore != null && mailStore.isConnected()) { mailStore.close(); } } catch (final MessagingException e1) { LogUtils.debugf(this, e1, "Unable to close message store."); } } }
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); 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(); }
public void checkNewMessage() { logger.debug("check new message..."); try { Session session = Session.getInstance(props, null); Store store = session.getStore(); store.connect(user, password); Folder inbox = store.getFolder(checkFolder); inbox.open(Folder.READ_WRITE); for (javax.mail.Message msg : inbox.getMessages()) { processMail(msg); } // inbox. } catch (Exception mex) { mex.printStackTrace(); } }
public Mail getEmail(int mailId, MailCredentials credentials, String salt) throws MessagingException, IOException { Properties properties = getServerProperties(credentials.getProtocol(), credentials.getHost(), "" + credentials.getPort()); Session session = Session.getDefaultInstance(properties); // connects to the message store Store store = session.getStore(credentials.getProtocol()); store.connect(credentials.getUsername(), credentials.getPassword()); // opens the inbox folder Folder folderInbox = store.getFolder("INBOX"); folderInbox.open(Folder.READ_ONLY); // fetches new messages from server int msgnum[] = new int[] { mailId }; Message[] messages = folderInbox.getMessages(msgnum); Mail mail = getMails(messages).get(0); // disconnect folderInbox.close(false); store.close(); return mail; }
public void changeMailStatus(int mailId, Flag flag, MailCredentials credentials) throws MessagingException { Properties properties = getServerProperties(credentials.getProtocol(), credentials.getHost(), "" + credentials.getPort()); Session session = Session.getDefaultInstance(properties); // connects to the message store Store store = session.getStore(credentials.getProtocol()); store.connect(credentials.getUsername(), credentials.getPassword()); // opens the inbox folder Folder folderInbox = store.getFolder("INBOX"); folderInbox.open(Folder.READ_WRITE); logger.debug("unread:" + folderInbox.getUnreadMessageCount() + ", new:" + folderInbox.getNewMessageCount()); // fetches new messages from server int msgnum[] = new int[] { mailId }; Message[] messages = folderInbox.getMessages(msgnum); if (messages.length == 1 && messages[0] != null) { messages[0].setFlag(flag, true); } folderInbox.close(false); store.close(); }
ImapFolder( Store store, String serverHost, String folderName, String userName, String password ) { this.isOpen = false; this.store = store; this.serverHost = serverHost; this.folderName = folderName; this.userName = userName; this.password = password; newMetaDataList = new ArrayList<MetaData>(); allMetaDataList = new ArrayList<MetaData>(); }
public MessageWrapper _getEmail( String hostName, MessageFilter[] messageFilters, Map<String, String> propertyMap ) { Properties mailProps = new Properties(); mailProps.putAll( propertyMap ); List<Message> messageList = new ArrayList<Message>( 10 ); MessageWrapper messageWrapper = null; try { Session emailSession = Session.getDefaultInstance( mailProps ); Store store = emailSession.getStore( propertyMap.get( PROTOCOL ) ); store.connect( hostName, propertyMap.get( USER_NAME ), propertyMap.get( PASSWORD ) ); Folder emailFolder = store.getFolder( propertyMap.get( FOLDER_NAME ) != null ? propertyMap.get( FOLDER_NAME ) : DEFAULT_FOLDER_NAME ); emailFolder.open( Folder.READ_WRITE ); Message[] messages = emailFolder.getMessages(); int messageCount = emailFolder.getMessageCount(); if ( messageCount > MAX_MESSAGES ) messageCount = MAX_MESSAGES; if ( log.isInfoEnabled() ) log.info( "Processing " + messageCount + " messages" ); for ( int i = 0; i < messageCount; i++ ) { if ( applyFilters( messages[i], messageFilters ) ) { messageList.add( messages[i] ); } } if ( messageList.size() == 0 ) throw new ScriptException( "Failed to find any email messages that met the criteria" ); Collections.sort( messageList, new DateComparator() ); String messageContent = null; String contentType = messageList.get( 0 ).getContentType(); if ( contentType.startsWith( "text/" ) ) messageContent = messageList.get( 0 ).getContent().toString(); else if ( messageList.get( 0 ).isMimeType( "multipart/*" ) ) messageContent = getTextFromMimeMultipart( (MimeMultipart) messageList.get( 0 ).getContent() ); else messageContent = messageList.get( 0 ).getContent().getClass().getName(); messageWrapper = new MessageWrapper( messageList.size(), messageList.get( 0 ).getFrom()[0].toString(), messageList.get( 0 ).getSubject(), messageContent, contentType ); emailFolder.close( false ); store.close(); } catch ( Exception e ) { e.printStackTrace(); throw new ScriptException( "Failed to find email" ); } return messageWrapper; }
private void ensureConnectedStore(Store store) throws MessagingException { if (!store.isConnected()) { LOGGER.debug("connect to sore"); store.connect(configuration.getUserName(), configuration.getPassword()); } }