Example usage for javax.mail.internet MimeMessage setFlag

List of usage examples for javax.mail.internet MimeMessage setFlag

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage setFlag.

Prototype

public void setFlag(Flags.Flag flag, boolean set) throws MessagingException 

Source Link

Document

Set the specified flag on this message to the specified value.

Usage

From source file:com.adaptris.mail.MailClientImp.java

/**
 * Reset the state of the message so that it is no longer marked as seen or deleted.
 * /*ww  w . j  a  v  a 2  s.c om*/
 * @param msg the Message to reset.
 * @throws Exception on error.
 */
@Override
public void resetMessage(MimeMessage msg) throws Exception {
    msg.setFlag(Flags.Flag.SEEN, false);
    msg.setFlag(Flags.Flag.DELETED, false);
    msg.saveChanges();
}

From source file:com.adaptris.mail.MailClientImp.java

@Override
public void setMessageRead(MimeMessage msg) throws MailException {
    try {/*from   w  w  w  .ja  v a2  s.  c  o  m*/
        if (msg.isSet(Flags.Flag.SEEN) || msg.isSet(Flags.Flag.DELETED)) {
            return;
        }
        msg.setFlag(Flags.Flag.SEEN, true);
        msg.setFlag(Flags.Flag.DELETED, deleteFlag);
        try {
            // When accessing a POP3 mailbox the sun provider
            // doesn't allow you to save changes to the message
            // status (curious)
            // To delete the messages, you should do setPurge(true);
            // This will work with imap mailboxes

            // Note that this does nothing for ComsNetClient
            msg.saveChanges();
        } catch (Exception e) {
            ;
        }
    } catch (Exception e) {
        throw new MailException(e);
    }
}

From source file:org.apache.axis2.transport.mail.MailClient.java

public int checkInbox(int mode) throws MessagingException, IOException {
    int numMessages = 0;

    if (mode == 0) {
        return 0;
    }/*from w  ww  .  ja  v  a 2 s .co m*/

    boolean show = (mode & SHOW_MESSAGES) > 0;
    boolean clear = (mode & CLEAR_MESSAGES) > 0;
    String action = (show ? "Show" : "") + ((show && clear) ? " and " : "") + (clear ? "Clear" : "");

    log.info(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();

    numMessages = msgs.length;

    if ((msgs.length == 0) && show) {
        log.info("No messages in inbox");
    }

    for (int i = 0; i < msgs.length; i++) {
        MimeMessage msg = (MimeMessage) msgs[i];

        if (show) {
            log.info("    From: " + msg.getFrom()[0]);
            log.info(" Subject: " + msg.getSubject());
            log.info(" Content: " + msg.getContent());
        }

        if (clear) {
            msg.setFlag(Flags.Flag.DELETED, true);
        }
    }

    inbox.close(true);
    store.close();

    return numMessages;
}

From source file:org.apache.hupa.server.preferences.InImapUserPreferencesStorage.java

/**
 * Opens the IMAP folder, deletes all messages which match the magic subject and
 * creates a new message with an attachment which contains the object serialized
 *///  w  w  w  . j  a  va  2 s.co  m
protected static void saveUserPreferencesInIMAP(Log logger, User user, Session session, IMAPStore iStore,
        String folderName, String subject, Object object)
        throws MessagingException, IOException, InterruptedException {
    IMAPFolder folder = (IMAPFolder) iStore.getFolder(folderName);

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

        // Serialize the object
        ByteArrayOutputStream fout = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(fout);
        oos.writeObject(object);
        oos.close();
        ByteArrayInputStream is = new ByteArrayInputStream(fout.toByteArray());

        // Create a new message with an attachment which has the serialized object
        MimeMessage message = new MimeMessage(session);
        message.setSubject(subject);

        Multipart multipart = new MimeMultipart();
        MimeBodyPart txtPart = new MimeBodyPart();
        txtPart.setContent("This message contains configuration used by Hupa, do not delete it", "text/plain");
        multipart.addBodyPart(txtPart);
        FileItem item = createPreferencesFileItem(is, subject, HUPA_DATA_MIME_TYPE);
        multipart.addBodyPart(MessageUtils.fileitemToBodypart(item));
        message.setContent(multipart);
        message.saveChanges();

        // It seems it's not possible to modify the content of an existing message using the API
        // So I delete the previous message storing the preferences and I create a new one
        Message[] msgs = folder.getMessages();
        for (Message msg : msgs) {
            if (subject.equals(msg.getSubject())) {
                msg.setFlag(Flag.DELETED, true);
            }
        }

        // It is necessary to copy the message before saving it (the same problem in AbstractSendMessageHandler)
        message = new MimeMessage((MimeMessage) message);
        message.setFlag(Flag.SEEN, true);
        folder.appendMessages(new Message[] { message });
        folder.close(true);
        logger.info("Saved preferences " + subject + " in imap folder " + folderName + " for user " + user);
    } else {
        logger.error("Unable to save preferences " + subject + " in imap folder " + folderName + " for user "
                + user);
    }
}

From source file:org.apache.axis2.transport.mail.SimpleMailListener.java

/**
 * Accept requests from a given TCP port and send them through the Axis
 * engine for processing.// w  w  w  . j a va  2s.  c om
 */
public void run() {

    // Accept and process requests from the socket
    if (running) {
        log.info("Mail listner strated to listen to the address " + user);
    }

    while (running) {
        log.info("Info started polling");
        try {
            synchronized (receiver) {
                receiver.connect();

                Message[] msgs = receiver.receiveMessages();

                if ((msgs != null) && (msgs.length > 0)) {
                    log.info(msgs.length + " Message(s) Found");

                    for (int i = 0; i < msgs.length; i++) {
                        MimeMessage msg = (MimeMessage) msgs[i];
                        try {
                            MessageContext mc = createMessageContextToMailWorker(msg);
                            msg.setFlag(Flags.Flag.DELETED, true);
                            if (mc == null) {
                                continue;
                            }
                            MailWorker worker = new MailWorker(configurationContext, mc);
                            this.configurationContext.getThreadPool().execute(worker);
                        } catch (Exception e) {
                            log.error("Error in SimpleMailListener - processing mail", e);
                        } finally {
                            // delete mail in any case
                        }
                    }
                }

                receiver.disconnect();
            }

        } catch (Exception e) {
            log.error("Error in SimpleMailListener", e);
        } finally {
            try {
                Thread.sleep(listenerWaitInterval);
            } catch (InterruptedException e) {
                log.warn("Error Encountered " + e);
            }
        }
    }

}

From source file:org.apache.axis2.transport.mail.MailRequestResponseClient.java

private Message getMessage(String requestMsgId) throws Exception {
    MimeMessage response = null;//from w  w  w  . ja v a2s.c  om
    Folder folder = store.getFolder(MailConstants.DEFAULT_FOLDER);
    folder.open(Folder.READ_WRITE);
    Message[] msgs = folder.getMessages();
    log.debug(msgs.length + " messages in mailbox");
    loop: for (Message m : msgs) {
        MimeMessage mimeMessage = (MimeMessage) m;
        String[] inReplyTo = mimeMessage.getHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO);
        log.debug("Found message " + mimeMessage.getMessageID() + " in reply to " + Arrays.toString(inReplyTo));
        if (inReplyTo != null && inReplyTo.length > 0) {
            for (int j = 0; j < inReplyTo.length; j++) {
                if (requestMsgId.equals(inReplyTo[j])) {
                    log.debug("Identified message " + mimeMessage.getMessageID() + " as the response to "
                            + requestMsgId + "; retrieving it from the store");
                    // We need to create a copy so that we can delete the original and close the folder
                    response = new MimeMessage(mimeMessage);
                    log.debug("Flagging message " + mimeMessage.getMessageID() + " for deletion");
                    mimeMessage.setFlag(Flags.Flag.DELETED, true);
                    break loop;
                }
            }
        }
        log.warn("Don't know what to do with message " + mimeMessage.getMessageID() + "; skipping");
    }
    folder.close(true);
    return response;
}

From source file:com.zotoh.maedr.device.PopIO.java

private void getMsgs() throws Exception {

    int cnt = _fd.getMessageCount();

    tlog().debug("PopIO: count of new messages: {}", cnt);
    if (cnt <= 0)
        return;/*  w ww . j  a  v a2s  . c  o m*/

    StringBuilder hds = new StringBuilder(512);
    Message[] msgs = _fd.getMessages();
    MimeMessage mm;
    StreamData data;
    String s;

    for (int i = 0; i < msgs.length; ++i) {
        mm = (MimeMessage) msgs[i];
        //TODO
        //_fd.getUID(mm);
        // read all the header lines
        hds.setLength(0);
        for (Enumeration<?> en = mm.getAllHeaderLines(); en.hasMoreElements();) {
            s = (String) en.nextElement();
            //                if (s.toLowerCase().indexOf(CTL) >= 0) {}
            //                else
            hds.append(s).append("\r\n");
        }

        data = StreamUte.readStream(mm.getRawInputStream());
        try {
            dispatch(new POP3Event(this, hds.toString(), data));
        } finally {
            if (_delete) {
                mm.setFlag(Flags.Flag.DELETED, true);
            }
        }
    }
}

From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java

/**
 * Creates the IMAP messages to be sent. Looks up access (email & pwd) from
 * LDAP, sets the values and returns the messages to be sent.
 * /*  www.  j  av a2s.  co  m*/
 * @param session Mail session 
 * @param emailAddr From email address
 * @param request Request from PS
 * @return Array of messages
 * @throws Exception 
 */
private Message[] createMessage(Session session, String emailAddr, SetMessageRequestType request)
        throws Exception {

    /*
    //DBG ONLY - Check about CC entry.
    List<String> ctlist = request.getContactTo();
    if (!CommonUtil.listNullorEmpty(ctlist)) {
        System.out.println("===> createMessage: TO="+ ctlist.get(0));
    }
    ctlist = request.getContactCC();
    if (!CommonUtil.listNullorEmpty(ctlist)) {
        System.out.println("===> createMessage: CC="+ ctlist.get(0));
    }
    ctlist = request.getContactBCC();
    if (!CommonUtil.listNullorEmpty(ctlist)) {
        System.out.println("===> createMessage: BCC="+ ctlist.get(0));
    }
    */
    MimeMessage message = new MimeMessage(session);

    if (!CommonUtil.listNullorEmpty(request.getContactTo())) {
        message.setRecipients(Message.RecipientType.TO, getInetAddresses(request.getContactTo())); //getInetAddresses(request, "To"));
    }

    if (!CommonUtil.listNullorEmpty(request.getContactCC())) {
        message.setRecipients(Message.RecipientType.CC, getInetAddresses(request.getContactCC())); //getInetAddresses(request, "CC"));
    }

    if (!CommonUtil.listNullorEmpty(request.getContactBCC())) {
        message.setRecipients(Message.RecipientType.BCC, getInetAddresses(request.getContactBCC())); //getInetAddresses(request, "BCC"));
    }

    message.setSubject(request.getSubject());

    // Adding headers doesn't seem to be supported currently in zimbra. 
    // Adding patientId to body instead temporarily 
    // message.addHeader("X-PATIENTID", request.getPatientId());
    StringBuilder sb = new StringBuilder();

    // Only add in PATIENTID first line if there is a patientId in session.
    if (!CommonUtil.strNullorEmpty(request.getPatientId())) {
        sb.append("PATIENTID=").append(request.getPatientId()).append("\n");
    }

    if (CommonUtil.strNullorEmpty(request.getBody())) {
        sb.append("");
    } else {
        sb.append(request.getBody());
    }

    message.setContent(sb.toString(), "text/plain");
    message.setFrom(new InternetAddress(emailAddr));
    message.setSentDate(new Date());

    List<String> labelList = request.getLabels();
    if (labelList.size() > 0) {
        String label = labelList.get(0);
        if (label.equalsIgnoreCase("starred")) {
            message.setFlag(Flags.Flag.FLAGGED, true);
        }
    }
    Message[] msgArr = new Message[1];
    msgArr[0] = message;
    return msgArr;
}

From source file:com.sonicle.webtop.mail.Service.java

public void processUploadToFolder(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    try {// ww  w .j a  va 2s .  c  o m
        MailAccount account = getAccount(request);
        String currentFolder = request.getParameter("folder");
        String uploadId = request.getParameter("uploadId");

        UploadedFile upfile = getUploadedFile(uploadId);
        InputStream in = new FileInputStream(upfile.getFile());
        MimeMessage msgContent = new MimeMessage(account.getMailSession(), in);
        FolderCache tomcache = account.getFolderCache(currentFolder);
        msgContent.setFlag(Flags.Flag.SEEN, true);
        tomcache.appendMessage(msgContent);
        new JsonResult().printTo(out);
    } catch (Exception exc) {
        logger.debug("Cannot upload to folder", exc);
        new JsonResult("Cannot upload to folder", exc).printTo(out);
    }
}

From source file:com.sonicle.webtop.mail.Service.java

public void processCopyAttachment(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    try {/*from w  ww .j  a v a 2  s  .  com*/
        MailAccount fromaccount = getAccount(request.getParameter("fromaccount"));
        MailAccount toaccount = getAccount(request.getParameter("toaccount"));
        fromaccount.checkStoreConnected();
        toaccount.checkStoreConnected();
        UserProfile profile = environment.getProfile();
        Locale locale = profile.getLocale();

        String pfromfolder = request.getParameter("fromfolder");
        String ptofolder = request.getParameter("tofolder");
        String puidmessage = request.getParameter("idmessage");
        String pidattach = request.getParameter("idattach");

        FolderCache frommcache = fromaccount.getFolderCache(pfromfolder);
        FolderCache tomcache = toaccount.getFolderCache(ptofolder);
        long uidmessage = Long.parseLong(puidmessage);
        Message m = frommcache.getMessage(uidmessage);

        HTMLMailData mailData = frommcache.getMailData((MimeMessage) m);
        Object content = mailData.getAttachmentPart(Integer.parseInt(pidattach)).getContent();

        // We can copy attachments only if the content is an eml. If it is
        // explicit simply treat it as message, otherwise try to decode the
        // stream as a mime message. If an error is thrown during parse, it 
        // means that the stream is reconducible to a valid mime-message.
        MimeMessage msgContent = null;
        if (content instanceof MimeMessage) {
            msgContent = new MimeMessage((MimeMessage) content);
        } else if (content instanceof IMAPInputStream) {
            try {
                msgContent = new MimeMessage(fromaccount.getMailSession(), (IMAPInputStream) content);
            } catch (MessagingException ex1) {
                logger.debug("Stream cannot be interpreted as MimeMessage", ex1);
            }
        }

        if (msgContent != null) {
            msgContent.setFlag(Flags.Flag.SEEN, true);
            tomcache.appendMessage(msgContent);
            new JsonResult().printTo(out);
        } else {
            new JsonResult(false, lookupResource(locale, MailLocaleKey.ERROR_ATTACHMENT_TYPE_NOT_SUPPORTED))
                    .printTo(out);
        }

    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
        new JsonResult(false, exc.getMessage()).printTo(out);
    }
}