Example usage for javax.mail Store getFolder

List of usage examples for javax.mail Store getFolder

Introduction

In this page you can find the example usage for javax.mail Store getFolder.

Prototype

public abstract Folder getFolder(URLName url) throws MessagingException;

Source Link

Document

Return a closed Folder object, corresponding to the given URLName.

Usage

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   ww w  .  j ava2 s. c o m*/
 * @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.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//www  . jav a 2s .c  o m
 */
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  ww .  java 2 s  .  c om
 */
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.//w w w .ja v  a  2  s.  com
 *
 * @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// www  .  ja  va  2s .co m
 * @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:org.apache.juddi.v3.tck.UDDI_090_Smtp_ExternalTest.java

/**
 * gets all current messages from the mail server and returns the number
 * of messages containing the string, messages containing the string are
 * deleted from the mail server String is the body of each message
 *
 * @return number of matching and deleted messages
 * @param contains a string to search for
 *//*www .j  a v  a2s.com*/
private static int fetchMail(String contains) {

    //final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

    /* Set the mail properties */
    Properties properties = TckPublisher.getProperties();
    // Set manual Properties

    int found = 0;
    Session session = Session.getDefaultInstance(properties, null);
    Store store = null;
    try {
        store = session.getStore("pop3");

        store.connect(properties.getProperty("mail.pop3.host"),
                Integer.parseInt(properties.getProperty("mail.pop3.port", "110")),
                properties.getProperty("mail.pop3.username"), properties.getProperty("mail.pop3.password"));
        /* Mention the folder name which you want to read. */
        // inbox = store.getDefaultFolder();
        // inbox = inbox.getFolder("INBOX");
        Folder inbox = store.getFolder("INBOX");

        /* Open the inbox using store. */
        inbox.open(Folder.READ_WRITE);

        Message messages[] = inbox.getMessages();

        for (int i = 0; i < messages.length; i++) {

            MimeMessageParser p = new MimeMessageParser(new MimeMessage(session, messages[i].getInputStream()));
            Enumeration allHeaders = p.getMimeMessage().getAllHeaders();
            while (allHeaders.hasMoreElements()) {
                Object j = allHeaders.nextElement();
                if (j instanceof javax.mail.Header) {
                    javax.mail.Header msg = (javax.mail.Header) j;
                    logger.info("XML as message header is " + msg.getValue());
                    if (msg.getValue().contains(contains)) {
                        //found it
                        messages[i].setFlag(Flags.Flag.DELETED, true);
                        found++;
                    }
                }
            }
            for (int k = 0; k < p.getAttachmentList().size(); k++) {
                InputStream is = p.getAttachmentList().get((k)).getInputStream();
                QuotedPrintableCodec qp = new QuotedPrintableCodec();
                // If "is" is not already buffered, wrap a BufferedInputStream
                // around it.
                if (!(is instanceof BufferedInputStream)) {
                    is = new BufferedInputStream(is);
                }
                int c;
                StringBuilder sb = new StringBuilder();
                System.out.println("Message : ");
                while ((c = is.read()) != -1) {
                    sb.append(c);
                    System.out.write(c);
                }
                is.close();
                String decoded = qp.decode(sb.toString());
                logger.info("decode message is " + decoded);
                if (decoded.contains(contains)) {
                    //found it
                    messages[i].setFlag(Flags.Flag.DELETED, true);
                    found++;
                }
            }

        }
        inbox.close(true);

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (store != null) {
            try {
                store.close();
            } catch (Exception ex) {
            }
        }
    }
    return found;
}

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  . ja v  a2s .co  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:org.nuxeo.cm.event.MailInjectionListener.java

public void handleEvent(Event event) throws ClientException {
    MailService mailService = Framework.getService(MailService.class);
    MessageActionPipe pipe = mailService.getPipe(MAILBOX_PIPE);

    Visitor visitor = new Visitor(pipe);
    Thread.currentThread().setContextClassLoader(Framework.class.getClassLoader());

    Folder rootFolder = null;/*from   ww w .j  a va2  s .c  o  m*/

    try (CoreSession session = CoreInstance.openCoreSessionSystem(null)) {
        // initialize context
        ExecutionContext initialExecutionContext = new ExecutionContext();
        initialExecutionContext.put(AbstractCaseManagementMailAction.CORE_SESSION_KEY, session);
        initialExecutionContext.put(AbstractCaseManagementMailAction.MIMETYPE_SERVICE_KEY,
                Framework.getService(MimetypeRegistry.class));
        initialExecutionContext.put(AbstractCaseManagementMailAction.CASEMANAGEMENT_SERVICE_KEY,
                Framework.getService(CaseDistributionService.class));

        // open store
        Store store = mailService.getConnectedStore(IMPORT_MAILBOX);
        rootFolder = store.getFolder(INBOX);
        rootFolder.open(Folder.READ_WRITE);
        Flags flags = new Flags();
        flags.add(Flag.SEEN);
        SearchTerm term = new FlagTerm(flags, false);
        Message[] unreadMessages = rootFolder.search(term);

        // perform import
        visitor.visit(unreadMessages, initialExecutionContext);

        // save session
        session.save();

        if (rootFolder.isOpen()) {
            try {
                rootFolder.close(true);
            } catch (MessagingException e) {
                log.error(e.getMessage(), e);
            }
        }
    } catch (MessagingException e) {
        log.error(e, e);
    }
}

From source file:dao.FetchEmailDAO.java

/**
 *
 * @return/* w  w  w .ja v a  2s .  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:org.apache.hupa.server.servlet.DownloadAttachmentServlet.java

/**
 * Handle to write back the requested attachment
 *///from   ww w  . ja  v  a 2s .c om
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    User user = (User) request.getSession().getAttribute(SConsts.USER_SESS_ATTR);
    if (user == null)
        throw new ServletException("Invalid session");

    String message_uuid = request.getParameter(SConsts.PARAM_UID);
    String attachmentName = request.getParameter(SConsts.PARAM_NAME);
    String folderName = request.getParameter(SConsts.PARAM_FOLDER);
    String mode = request.getParameter(SConsts.PARAM_MODE);
    boolean inline = "inline".equals(mode);
    if (!inline) {
        response.setHeader("Content-disposition", "attachment; filename=" + attachmentName + "");
    }
    InputStream in = null;
    OutputStream out = response.getOutputStream();

    IMAPFolder folder = null;
    try {
        Store store = cache.get(user);
        folder = (IMAPFolder) store.getFolder(folderName);
        if (folder.isOpen() == false) {
            folder.open(Folder.READ_ONLY);
        }
        Message m = folder.getMessageByUID(Long.parseLong(message_uuid));

        Object content = m.getContent();
        Part part = MessageUtils.handleMultiPart(logger, content, attachmentName);
        if (part.getContentType() != null) {
            response.setContentType(part.getContentType());
        } else {
            response.setContentType("application/download");
        }

        handleAttachmentData(request, m, attachmentName, part.getInputStream(), out);
        return;
    } catch (Exception e) {
        logger.error("Error while downloading attachment " + attachmentName + " of message " + message_uuid
                + " for user " + user.getName(), e);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
        if (folder != null) {
            try {
                folder.close(false);
            } catch (MessagingException e) {
            }
        }
    }
}