Example usage for javax.mail Folder READ_WRITE

List of usage examples for javax.mail Folder READ_WRITE

Introduction

In this page you can find the example usage for javax.mail Folder READ_WRITE.

Prototype

int READ_WRITE

To view the source code for javax.mail Folder READ_WRITE.

Click Source Link

Document

The state and contents of this folder can be modified.

Usage

From source file:org.apache.hupa.server.handler.AbstractSendMessageHandler.java

/**
 * Save the message in the sent folder//ww w  . jav  a 2s.  c  o m
 * 
 * @param user
 * @param message
 * @throws MessagingException
 * @throws IOException 
 */
protected void saveSentMessage(User user, Message message) throws MessagingException, IOException {
    IMAPStore iStore = cache.get(user);
    IMAPFolder folder = (IMAPFolder) iStore.getFolder(user.getSettings().getSentFolderName());

    if (folder.exists() || folder.create(IMAPFolder.READ_WRITE)) {
        if (folder.isOpen() == false) {
            folder.open(Folder.READ_WRITE);
        }

        // It is necessary to copy the message, before putting it
        // in the sent folder. If not, it is not guaranteed that it is 
        // stored in ascii and is not possible to get the attachments
        // size. message.saveChanges() doesn't fix the problem.
        // There are tests which demonstrate this.
        message = new MimeMessage((MimeMessage) message);

        message.setFlag(Flag.SEEN, true);
        folder.appendMessages(new Message[] { message });

        try {
            folder.close(false);
        } catch (MessagingException e) {
            // we don't care on close
        }
    }
}

From source file:com.cubusmail.mail.imap.IMAPMailFolder.java

public Message getMessageById(long messageId) throws MessagingException {

    if (!this.folder.isOpen()) {
        this.folder.open(Folder.READ_WRITE);
    }/*ww w  .jav a 2s . c o m*/
    return this.folder.getMessageByUID(messageId);
}

From source file:com.cubusmail.mail.imap.IMAPMailFolder.java

public Message[] getMessagesById(long[] messageIds) throws MessagingException {

    if (!this.folder.isOpen()) {
        this.folder.open(Folder.READ_WRITE);
    }/*from   w ww  . j av  a  2  s  .c o m*/
    return this.folder.getMessagesByUID(messageIds);
}

From source file:com.cubusmail.mail.imap.IMAPMailbox.java

public void emptyFolder(String folderId) throws MailFolderException {

    IMailFolder folder = getMailFolderById(folderId);

    try {//from w w w. j  av  a 2s  .  c  o  m
        if (!folder.isOpen()) {
            folder.open(Folder.READ_WRITE);
        }

        if (folder.getMessageCount() > 0) {
            Message[] msgs = folder.retrieveMessages(null);
            for (int i = 0; i < folder.getMessageCount(); i++) {
                msgs[i].setFlag(Flags.Flag.DELETED, true);
            }
        }
        folder.close(true);
    } catch (MessagingException ex) {
        throw new MailFolderException(IErrorCodes.EXCEPTION_FOLDER_EMPTY, ex, folder);
    }
}

From source file:com.naryx.tagfusion.cfm.mail.cfPOP3.java

private Folder openFolder(cfSession _Session, Store popStore) throws cfmRunTimeException {
    try {//  w  w  w  . j a  v a2 s.  com
        Folder folder = popStore.getDefaultFolder();
        Folder popFolder = folder.getFolder("INBOX");
        popFolder.open(Folder.READ_WRITE);
        return popFolder;
    } catch (Exception E) {
        throw newRunTimeException(E.getMessage());
    }
}

From source file:org.apache.hupa.server.service.SendMessageBaseServiceImpl.java

/**
 * Save the message in the sent folder//from  w  w w  .j a  v a2  s  .  co m
 *
 * @param user
 * @param message
 * @throws MessagingException
 * @throws IOException
 */
protected void saveSentMessage(User user, Message message) throws MessagingException, IOException {
    IMAPStore iStore = cache.get(user);
    IMAPFolder folder = (IMAPFolder) iStore.getFolder(user.getSettings().getSentFolderName());

    if (folder.exists() || folder.create(IMAPFolder.READ_WRITE)) {
        if (folder.isOpen() == false) {
            folder.open(Folder.READ_WRITE);
        }

        // It is necessary to copy the message, before putting it
        // in the sent folder. If not, it is not guaranteed that it is
        // stored in ascii and is not possible to get the attachments
        // size. message.saveChanges() doesn't fix the problem.
        // There are tests which demonstrate this.
        message = new MimeMessage((MimeMessage) message);

        message.setFlag(Flag.SEEN, true);
        folder.appendMessages(new Message[] { message });

        try {
            folder.close(false);
        } catch (MessagingException e) {
            // we don't care on close
        }
    }
}

From source file:com.cws.esolutions.core.utils.EmailUtils.java

/**
 * Processes and sends an email message as generated by the requesting
 * application. This method is utilized with a JNDI datasource.
 *
 * @param dataSource - The email message
 * @param authRequired - <code>true</code> if authentication is required, <code>false</code> otherwise
 * @param authList - If authRequired is true, this must be populated with the auth info
 * @return List - The list of email messages in the mailstore
 * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs during processing
 *///from  w  w  w  . j  a va2 s  .c o  m
public static final synchronized List<EmailMessage> readEmailMessages(final Properties dataSource,
        final boolean authRequired, final List<String> authList) throws MessagingException {
    final String methodName = EmailUtils.CNAME
            + "#readEmailMessages(final Properties dataSource, final boolean authRequired, final List<String> authList) throws MessagingException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("dataSource: {}", dataSource);
        DEBUGGER.debug("authRequired: {}", authRequired);
        DEBUGGER.debug("authList: {}", authList);
    }

    Folder mailFolder = null;
    Session mailSession = null;
    Folder archiveFolder = null;
    List<EmailMessage> emailMessages = null;

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.HOUR, -24);

    final Long TIME_PERIOD = cal.getTimeInMillis();
    final URLName URL_NAME = (authRequired)
            ? new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"),
                    Integer.parseInt(dataSource.getProperty("port")), null, authList.get(0), authList.get(1))
            : new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"),
                    Integer.parseInt(dataSource.getProperty("port")), null, null, null);

    if (DEBUG) {
        DEBUGGER.debug("timePeriod: {}", TIME_PERIOD);
        DEBUGGER.debug("URL_NAME: {}", URL_NAME);
    }

    try {
        // Set up mail session
        mailSession = (authRequired) ? Session.getDefaultInstance(dataSource, new SMTPAuthenticator())
                : Session.getDefaultInstance(dataSource);

        if (DEBUG) {
            DEBUGGER.debug("mailSession: {}", mailSession);
        }

        if (mailSession == null) {
            throw new MessagingException("Unable to configure email services");
        }

        mailSession.setDebug(DEBUG);
        Store mailStore = mailSession.getStore(URL_NAME);
        mailStore.connect();

        if (DEBUG) {
            DEBUGGER.debug("mailStore: {}", mailStore);
        }

        if (!(mailStore.isConnected())) {
            throw new MessagingException("Failed to connect to mail service. Cannot continue.");
        }

        mailFolder = mailStore.getFolder("inbox");
        archiveFolder = mailStore.getFolder("archive");

        if (!(mailFolder.exists())) {
            throw new MessagingException("Requested folder does not exist. Cannot continue.");
        }

        mailFolder.open(Folder.READ_WRITE);

        if ((!(mailFolder.isOpen())) || (!(mailFolder.hasNewMessages()))) {
            throw new MessagingException("Failed to open requested folder. Cannot continue");
        }

        if (!(archiveFolder.exists())) {
            archiveFolder.create(Folder.HOLDS_MESSAGES);
        }

        Message[] mailMessages = mailFolder.getMessages();

        if (mailMessages.length == 0) {
            throw new MessagingException("No messages were found in the provided store.");
        }

        emailMessages = new ArrayList<EmailMessage>();

        for (Message message : mailMessages) {
            if (DEBUG) {
                DEBUGGER.debug("MailMessage: {}", message);
            }

            // validate the message here
            String messageId = message.getHeader("Message-ID")[0];
            Long messageDate = message.getReceivedDate().getTime();

            if (DEBUG) {
                DEBUGGER.debug("messageId: {}", messageId);
                DEBUGGER.debug("messageDate: {}", messageDate);
            }

            // only get emails for the last 24 hours
            // this should prevent us from pulling too
            // many emails
            if (messageDate >= TIME_PERIOD) {
                // process it
                Multipart attachment = (Multipart) message.getContent();
                Map<String, InputStream> attachmentList = new HashMap<String, InputStream>();

                for (int x = 0; x < attachment.getCount(); x++) {
                    BodyPart bodyPart = attachment.getBodyPart(x);

                    if (!(Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()))) {
                        continue;
                    }

                    attachmentList.put(bodyPart.getFileName(), bodyPart.getInputStream());
                }

                List<String> toList = new ArrayList<String>();
                List<String> ccList = new ArrayList<String>();
                List<String> bccList = new ArrayList<String>();
                List<String> fromList = new ArrayList<String>();

                for (Address from : message.getFrom()) {
                    fromList.add(from.toString());
                }

                if ((message.getRecipients(RecipientType.TO) != null)
                        && (message.getRecipients(RecipientType.TO).length != 0)) {
                    for (Address to : message.getRecipients(RecipientType.TO)) {
                        toList.add(to.toString());
                    }
                }

                if ((message.getRecipients(RecipientType.CC) != null)
                        && (message.getRecipients(RecipientType.CC).length != 0)) {
                    for (Address cc : message.getRecipients(RecipientType.CC)) {
                        ccList.add(cc.toString());
                    }
                }

                if ((message.getRecipients(RecipientType.BCC) != null)
                        && (message.getRecipients(RecipientType.BCC).length != 0)) {
                    for (Address bcc : message.getRecipients(RecipientType.BCC)) {
                        bccList.add(bcc.toString());
                    }
                }

                EmailMessage emailMessage = new EmailMessage();
                emailMessage.setMessageTo(toList);
                emailMessage.setMessageCC(ccList);
                emailMessage.setMessageBCC(bccList);
                emailMessage.setEmailAddr(fromList);
                emailMessage.setMessageAttachments(attachmentList);
                emailMessage.setMessageDate(message.getSentDate());
                emailMessage.setMessageSubject(message.getSubject());
                emailMessage.setMessageBody(message.getContent().toString());
                emailMessage.setMessageSources(message.getHeader("Received"));

                if (DEBUG) {
                    DEBUGGER.debug("emailMessage: {}", emailMessage);
                }

                emailMessages.add(emailMessage);

                if (DEBUG) {
                    DEBUGGER.debug("emailMessages: {}", emailMessages);
                }
            }

            // archive it
            archiveFolder.open(Folder.READ_WRITE);

            if (archiveFolder.isOpen()) {
                mailFolder.copyMessages(new Message[] { message }, archiveFolder);
                message.setFlag(Flags.Flag.DELETED, true);
            }
        }
    } catch (IOException iox) {
        throw new MessagingException(iox.getMessage(), iox);
    } catch (MessagingException mex) {
        throw new MessagingException(mex.getMessage(), mex);
    } finally {
        try {
            if ((mailFolder != null) && (mailFolder.isOpen())) {
                mailFolder.close(true);
            }

            if ((archiveFolder != null) && (archiveFolder.isOpen())) {
                archiveFolder.close(false);
            }
        } catch (MessagingException mx) {
            ERROR_RECORDER.error(mx.getMessage(), mx);
        }
    }

    return emailMessages;
}

From source file:com.googlecode.gmail4j.javamail.ImapGmailClient.java

/**
 * Moves given {@link GmailMessage}'s to {@link ImapGmailLabel.TRASH} folder.
 *
 * @param gmailMessages {@link GmailMessage} message(s)
 * @throws GmailException if unable to move {@link GmailMessage}'s to
 * the Trash Folder/*from w ww  .  j a v  a2  s  .c o m*/
 */
public void moveToTrash(final GmailMessage[] gmailMessages) {
    if (gmailMessages == null || gmailMessages.length <= 0) {
        LOG.warn("ImapGmailClient requires GmailMessage(s) to move" + " to move messages to trash folder");
        return;
    }
    Folder folder = null;

    try {
        final Store store = openGmailStore();
        folder = getFolder(this.srcFolder, store);
        if (!folder.isOpen()) {
            folder.open(Folder.READ_WRITE);
        }

        List<Message> markedMsgList = new ArrayList<Message>();
        for (GmailMessage gmailMessage : gmailMessages) {
            // get only messages that match to the specified message number
            Message message = folder.getMessage(gmailMessage.getMessageNumber());
            message.setFlag(Flags.Flag.SEEN, true);
            // mark message as delete
            message.setFlag(Flags.Flag.DELETED, true);
            markedMsgList.add(message);
        }

        Folder trash = getFolder(ImapGmailLabel.TRASH.getName(), store);
        if (folder.getURLName().equals(trash.getURLName())) {
            LOG.warn("ImapGmailClient trying to move GmailMessage(s) within"
                    + " same folder(ImapGmailLabel.TRASH.getName())");
        }
        // move the marked messages to trash folder
        if (!markedMsgList.isEmpty()) {
            folder.copyMessages(markedMsgList.toArray(new Message[0]), trash);
        }
    } catch (Exception e) {
        throw new GmailException("ImapGmailClient failed moving GmailMessage(s)" + " to trash folder: " + e);
    } finally {
        closeFolder(folder);
    }
}

From source file:com.cubusmail.server.mail.imap.IMAPMailbox.java

public void emptyFolder(String folderId) throws MailFolderException {

    IMailFolder folder = getMailFolderById(folderId);

    try {//from w w  w .ja va2  s  . c  o  m
        if (!folder.isOpen()) {
            folder.open(Folder.READ_WRITE);
        }

        if (folder.getMessageCount() > 0) {
            Message[] msgs = folder.retrieveMessages(null, true, null, null);
            for (int i = 0; i < folder.getMessageCount(); i++) {
                msgs[i].setFlag(Flags.Flag.DELETED, true);
            }
        }
        folder.close(true);
    } catch (MessagingException ex) {
        throw new MailFolderException(IErrorCodes.EXCEPTION_FOLDER_EMPTY, ex, folder);
    }
}

From source file:org.springframework.integration.mail.ImapMailReceiverTests.java

private AbstractMailReceiver receiveAndMarkAsReadDontDeleteGuts(AbstractMailReceiver receiver, Message msg1,
        Message msg2) throws NoSuchFieldException, IllegalAccessException, MessagingException {
    ((ImapMailReceiver) receiver).setShouldMarkMessagesAsRead(true);
    receiver = spy(receiver);/*from  ww  w  . j  a  v  a  2 s .  c o m*/
    receiver.setBeanFactory(mock(BeanFactory.class));
    receiver.afterPropertiesSet();
    Field folderField = AbstractMailReceiver.class.getDeclaredField("folder");
    folderField.setAccessible(true);
    Folder folder = mock(Folder.class);
    given(folder.getPermanentFlags()).willReturn(new Flags(Flags.Flag.USER));
    folderField.set(receiver, folder);

    final Message[] messages = new Message[] { msg1, msg2 };

    willAnswer(invocation -> {
        DirectFieldAccessor accessor = new DirectFieldAccessor(invocation.getMock());
        int folderOpenMode = (Integer) accessor.getPropertyValue("folderOpenMode");
        if (folderOpenMode != Folder.READ_WRITE) {
            throw new IllegalArgumentException("Folder had to be open in READ_WRITE mode");
        }

        return null;
    }).given(receiver).openFolder();

    willAnswer(invocation -> messages).given(receiver).searchForNewMessages();

    willAnswer(invocation -> null).given(receiver).fetchMessages(messages);
    receiver.receive();
    return receiver;
}