List of usage examples for javax.mail Folder READ_WRITE
int READ_WRITE
To view the source code for javax.mail Folder READ_WRITE.
Click Source Link
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 2 s.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:nl.ordina.bag.etl.mail.loader.POP3MutatiesFileLoader.java
@Override public void processMessages() { try {/*from www .j a v a 2 s . com*/ Session session = Session.getDefaultInstance(new Properties(), null); Store store = session.getStore(protocol); if (port == 0) store.connect(host, username, password); else store.connect(host, port, username, password); Folder folder = store.getFolder(folderName); if (folder == null) throw new RuntimeException("Folder " + folderName + " not found!"); folder.open(Folder.READ_WRITE); try { Message[] messages = folder.getMessages(); for (Message message : messages) { backup(message); messageHandler.handle(message); message.setFlags(new Flags(Flags.Flag.DELETED), true); } } finally { folder.close(true); store.close(); } } catch (MessagingException | IOException | JAXBException e) { throw new ProcessingException(e); } }
From source file:FolderModel.java
public void setFolder(Folder what) throws MessagingException { if (what != null) { // opened if needed if (!what.isOpen()) { what.open(Folder.READ_WRITE); }/*from w ww .j a v a 2 s . com*/ // get the messages messages = what.getMessages(); cached = new String[messages.length][]; } else { messages = null; cached = null; } // close previous folder and switch to new folder if (folder != null) folder.close(true); folder = what; fireTableDataChanged(); }
From source file:jp.mamesoft.mailsocketchat.Mail.java
public void run() { while (true) { try {//www .ja v a2s.co m System.out.println("????"); Properties props = System.getProperties(); // Get a Session object Session session = Session.getInstance(props, null); // session.setDebug(true); // Get a Store object Store store = session.getStore("imaps"); // Connect store.connect("imap.gmail.com", 993, Mailsocketchat.mail_user, Mailsocketchat.mail_pass); System.out.println("??????"); // Open a Folder Folder folder = store.getFolder("INBOX"); if (folder == null || !folder.exists()) { System.out.println("IMAP??????"); System.exit(1); } folder.open(Folder.READ_WRITE); // Add messageCountListener to listen for new messages folder.addMessageCountListener(new MessageCountAdapter() { public void messagesAdded(MessageCountEvent ev) { Message[] msgs = ev.getMessages(); // Just dump out the new messages for (int i = 0; i < msgs.length; i++) { try { System.out.println("?????"); InternetAddress addrfrom = (InternetAddress) msgs[i].getFrom()[0]; String subject = msgs[i].getSubject(); if (subject == null) { subject = ""; } Pattern hashtag_p = Pattern.compile("#(.+)"); Matcher hashtag_m = hashtag_p.matcher(subject); if (subject.equals("#")) { hashtag = null; } else if (hashtag_m.find()) { hashtag = hashtag_m.group(1); } String comment = msgs[i].getContent().toString().replaceAll("\r\n", " "); comment = comment.replaceAll("\n", " "); comment = comment.replaceAll("\r", " "); JSONObject data = new JSONObject(); data.put("comment", comment); if (hashtag != null) { data.put("channel", hashtag); } if (!comment.equals("") && !comment.equals(" ") && !comment.equals(" ")) { Mailsocketchat.socket.emit("say", data); System.out.println("????"); } // if (subject.equals("push") || subject.equals("Push") || subject.equals("")) { Send(addrfrom.getAddress(), 2); Mailsocketchat.push = true; Mailsocketchat.repeat = false; Mailsocketchat.address = addrfrom.getAddress(); repeatthread.cancel(); repeatthread = null; System.out.println("?????"); } else if (subject.equals("fetch") || subject.equals("Fetch") || subject.equals("?")) { Send(addrfrom.getAddress(), 3); Mailsocketchat.push = false; Mailsocketchat.repeat = false; repeatthread.cancel(); repeatthread = null; System.out.println("??????"); } else if (subject.equals("repeat") || subject.equals("Repeat") || subject.equals("")) { Send(addrfrom.getAddress(), 7); Mailsocketchat.push = false; Mailsocketchat.repeat = true; Mailsocketchat.address = addrfrom.getAddress(); if (repeatthread == null) { repeatthread = new Repeat(); repeat = new Timer(); } repeat.schedule(repeatthread, 0, 30 * 1000); System.out.println("?????"); } else if (subject.equals("list") || subject.equals("List") || subject.equals("")) { Send(addrfrom.getAddress(), 4); } else if (subject.equals("help") || subject.equals("Help") || subject.equals("")) { Send(addrfrom.getAddress(), 5); } else { if (!Mailsocketchat.push && !Mailsocketchat.repeat) { Send(addrfrom.getAddress(), 0); } else if (comment.equals("") || comment.equals(" ") || comment.equals(" ")) { Send(addrfrom.getAddress(), 5); } } } catch (IOException ioex) { System.out.println( "??????????"); } catch (MessagingException mex) { System.out.println( "??????????"); } } } }); // Check mail once in "freq" MILLIseconds int freq = 1000; //?? boolean supportsIdle = false; try { if (folder instanceof IMAPFolder) { IMAPFolder f = (IMAPFolder) folder; f.idle(); supportsIdle = true; } } catch (FolderClosedException fex) { throw fex; } catch (MessagingException mex) { supportsIdle = false; } for (;;) { if (supportsIdle && folder instanceof IMAPFolder) { IMAPFolder f = (IMAPFolder) folder; f.idle(); } else { Thread.sleep(freq); // sleep for freq milliseconds // This is to force the IMAP server to send us // EXISTS notifications. folder.getMessageCount(); } } } catch (Exception ex) { System.out.println("??????????"); } } }
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 w w w . j ava 2 s . 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:org.apache.hupa.server.handler.DeleteAllMessagesHandler.java
protected Message[] getMessagesToDelete(DeleteAllMessages action) throws ActionException { User user = getUser();/* www .j a v a 2 s.c o m*/ try { logger.info("Delete all messages in folder " + action.getFolder() + " for user " + user); IMAPStore store = cache.get(user); IMAPFolder folder = (IMAPFolder) store.getFolder(action.getFolder().getFullName()); if (folder.isOpen() == false) { folder.open(Folder.READ_WRITE); } return folder.getMessages(); } catch (MessagingException e) { String errorMsg = "Error while deleting all messages in folder " + action.getFolder() + " for user " + user; logger.error(errorMsg, e); throw new ActionException(errorMsg); } }
From source file:org.apache.hupa.server.handler.SetFlagsHandler.java
@Override protected GenericResult executeInternal(SetFlag action, ExecutionContext context) throws ActionException { User user = getUser();/*from ww w .j a v a 2 s . c o m*/ IMAPFolder folder = action.getFolder(); ArrayList<Long> uids = action.getUids(); com.sun.mail.imap.IMAPFolder f = null; try { IMAPStore store = cache.get(user); f = (com.sun.mail.imap.IMAPFolder) store.getFolder(folder.getFullName()); if (f.isOpen() == false) { f.open(Folder.READ_WRITE); } Message[] msgs = f.getMessagesByUID(toArray(uids)); Flag flag = JavamailUtil.convert(action.getFlag()); Flags flags = new Flags(); flags.add(flag); f.setFlags(msgs, flags, action.getValue()); return new GenericResult(); } catch (MessagingException e) { String errorMsg = "Error while setting flags of messages with uids " + uids + " for user " + user; logger.error(errorMsg, e); throw new ActionException(errorMsg, e); } finally { if (f != null && f.isOpen()) { try { f.close(false); } catch (MessagingException e) { // ignore on close } } } }
From source file:org.apache.hupa.server.handler.MoveMessageHandler.java
protected MoveMessageResult executeInternal(MoveMessage action, ExecutionContext context) throws ActionException { User user = getUser();/* ww w.ja v a 2 s .co m*/ try { IMAPStore store = cache.get(user); IMAPFolder folder = (IMAPFolder) store.getFolder(action.getOldFolder().getFullName()); if (folder.isOpen() == false) { folder.open(Folder.READ_WRITE); } Message m = folder.getMessageByUID(action.getMessageUid()); Message[] mArray = new Message[] { m }; folder.copyMessages(mArray, store.getFolder(action.getNewFolder().getFullName())); folder.setFlags(mArray, new Flags(Flags.Flag.DELETED), true); try { folder.expunge(mArray); folder.close(false); } catch (MessagingException e) { // prolly UID expunge is not supported folder.close(true); } return new MoveMessageResult(); } catch (MessagingException e) { logger.error("Error while moving message " + action.getMessageUid() + " from folder " + action.getOldFolder() + " to " + action.getNewFolder(), e); throw new ActionException(e); } }
From source file:org.xwiki.contrib.mail.internal.AbstractMailStore.java
/** * @param folder// ww w .j a v a 2s . 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:org.apache.hupa.server.handler.TagMessagesHandler.java
protected GenericResult executeInternal(TagMessage action, ExecutionContext context) throws ActionException { User user = getUser();//from w w w. j a v a 2 s . c o m ArrayList<Long> uids = action.getMessageUids(); Tag tag = action.getTag(); IMAPFolder folder = null; try { IMAPStore store = cache.get(user); folder = (IMAPFolder) store.getFolder(action.getFolder().getFullName()); if (folder.isOpen() == false) { folder.open(Folder.READ_WRITE); } for (Message m : folder.getMessagesByUID(copyUids(uids))) { m.getFlags().add(tag.toString()); } return new GenericResult(); } catch (MessagingException e) { logger.error("Error while tag messages " + uids.toString() + " for user " + user + " of folder" + action.getFolder(), e); throw new ActionException(e); } finally { try { folder.close(false); } catch (MessagingException e) { // ignore on close } } }