Example usage for javax.mail Message isSet

List of usage examples for javax.mail Message isSet

Introduction

In this page you can find the example usage for javax.mail Message isSet.

Prototype

public boolean isSet(Flags.Flag flag) throws MessagingException 

Source Link

Document

Check whether the flag specified in the flag argument is set in this message.

Usage

From source file:com.cubusmail.mail.util.MessageUtils.java

/**
 * @param msg/*from w ww .j a va2  s . co m*/
 * @return
 * @throws MessagingException
 */
public static boolean isMessageReadFlag(Message msg) throws MessagingException {

    return msg.isSet(Flags.Flag.SEEN);

}

From source file:com.cubusmail.gwtui.server.services.ConvertUtil.java

/**
 * @param folder/*from   w  w w  .ja v a 2 s .c  om*/
 * @param msg
 * @param result
 * @throws MessagingException
 */
public static void convertToStringArray(IMailFolder folder, Message msg, String[] result, DateFormat dateFormat,
        NumberFormat decimalFormat) throws MessagingException {

    result[MessageListFields.ID.ordinal()] = Long.toString(folder.getUID(msg));
    try {
        result[MessageListFields.ATTACHMENT_FLAG.ordinal()] = Boolean
                .toString(MessageUtils.hasAttachments(msg));
    } catch (IOException e) {
        // do nothing
    }
    result[MessageListFields.READ_FLAG.ordinal()] = Boolean.toString(msg.isSet(Flags.Flag.SEEN));
    result[MessageListFields.DELETED_FLAG.ordinal()] = Boolean.toString(msg.isSet(Flags.Flag.DELETED));
    result[MessageListFields.ANSWERED_FLAG.ordinal()] = Boolean.toString(msg.isSet(Flags.Flag.ANSWERED));
    result[MessageListFields.DRAFT_FLAG.ordinal()] = Boolean.toString(msg.isSet(Flags.Flag.DRAFT));
    result[MessageListFields.PRIORITY.ordinal()] = Integer.toString(MessageUtils.getMessagePriority(msg));
    if (!StringUtils.isEmpty(msg.getSubject())) {
        result[MessageListFields.SUBJECT.ordinal()] = msg.getSubject();
    }
    result[MessageListFields.FROM.ordinal()] = MessageUtils.getMailAdressString(msg.getFrom(),
            AddressStringType.PERSONAL);
    result[MessageListFields.TO.ordinal()] = MessageUtils
            .getMailAdressString(msg.getRecipients(RecipientType.TO), AddressStringType.PERSONAL);
    if (msg.getSentDate() != null) {
        result[MessageListFields.DATE.ordinal()] = dateFormat.format(msg.getSentDate());
    }
    result[MessageListFields.SIZE.ordinal()] = MessageUtils
            .formatPartSize(MessageUtils.calculateAttachmentSize(msg.getSize()), decimalFormat);
}

From source file:com.cubusmail.mail.util.MessageUtils.java

/**
 * @param msg//from   w w w  .  java 2 s . com
 * @param flag
 * @param readFlag
 * @throws MessagingException
 */
public static void setMessageFlag(Message msg, Flags.Flag flag, boolean readFlag) throws MessagingException {

    boolean currentFlag = msg.isSet(flag);

    if (currentFlag != readFlag) {
        msg.setFlag(flag, readFlag);
    }
}

From source file:com.cubusmail.server.services.ConvertUtil.java

/**
 * @param folder/*from w  w w .  j av  a 2s.  c o  m*/
 * @param msg
 * @param result
 * @throws MessagingException
 */
private static void convertToStringArray(IMAPFolder folder, Message msg, GWTMessageRecord result,
        DateFormat dateFormat, NumberFormat decimalFormat) throws MessagingException {

    result.setId(Long.toString(folder.getUID(msg)));
    try {
        result.setAttachmentImage(MessageUtils.hasAttachments(msg) ? ImageProvider.MSG_ATTACHMENT : null);
    } catch (IOException e) {
        // do nothing
    }
    GWTMessageFlags flags = new GWTMessageFlags();
    flags.setDeleted(msg.isSet(Flags.Flag.DELETED));
    flags.setUnread(!msg.isSet(Flags.Flag.SEEN));
    flags.setAnswered(msg.isSet(Flags.Flag.ANSWERED));
    flags.setDraft(msg.isSet(Flags.Flag.DRAFT));
    result.setFlags(flags);

    result.setProrityImage(getPriorityImage(msg));
    result.setSubject(HtmlUtils.htmlEscape(msg.getSubject()));

    result.setFrom(
            HtmlUtils.htmlEscape(MessageUtils.getMailAdressString(msg.getFrom(), AddressStringType.PERSONAL)));
    result.setTo(HtmlUtils.htmlEscape(
            MessageUtils.getMailAdressString(msg.getRecipients(RecipientType.TO), AddressStringType.PERSONAL)));
    if (msg.getSentDate() != null) {
        result.setSendDateString(HtmlUtils.htmlEscape(dateFormat.format(msg.getSentDate())));
        result.setSendDate(msg.getSentDate());
    }

    int msgSize = MessageUtils.calculateAttachmentSize(msg.getSize());
    result.setSizeString(HtmlUtils.htmlEscape(MessageUtils.formatPartSize(msgSize, decimalFormat)));
    result.setSize(msgSize);
}

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 ww  . j  a  va 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:com.agiletec.plugins.jpwebmail.apsadmin.webmail.folder.WebmailAction.java

protected boolean isFlag(Message message, Flag flag) {
    try {// w  w w . jav  a2  s  . c  o  m
        Folder folder = message.getFolder();
        super.checkFolder(folder);
        return message.isSet(flag);
    } catch (Throwable t) {
        _logger.error("Error checking flag '" + flag + "' on message ", t);
    }
    return false;
}

From source file:org.openadaptor.auxil.connector.mail.MailConnection.java

/**
 * @return true if the read flag has been set on the supplied message
 *
 * @throws MessagingException if there was a problem
 *//*from   www.  ja  va2 s  .c o  m*/
public boolean isReadFlagSet(Message msg) throws MessagingException {
    return msg.isSet(Flags.Flag.SEEN);
}

From source file:org.openadaptor.auxil.connector.mail.MailConnection.java

/**
 * @return the body from the supplied message or null if there was a problem
 *
 * @throws MessagingException if there was a problem reading the message status
 * @throws IOException if the body content could not be retrieved
 *///w ww.j  av a  2s .c o  m
public Object getBody(Message msg) throws MessagingException, IOException {
    if (msg != null && !msg.isExpunged() && !msg.isSet(Flags.Flag.DELETED))
        return msg.getContent();

    return null;
}

From source file:ch.entwine.weblounge.bridge.mail.MailAggregator.java

/**
 * {@inheritDoc}//from w ww  . j  av a2  s .c o  m
 * 
 * @see ch.entwine.weblounge.common.scheduler.JobWorker#execute(java.lang.String,
 *      java.util.Dictionary)
 */
public void execute(String name, Dictionary<String, Serializable> ctx) throws JobException {

    Site site = (Site) ctx.get(Site.class.getName());

    // Make sure the site is ready to accept content
    if (site.getContentRepository().isReadOnly()) {
        logger.warn("Unable to publish e-mail messages to site '{}': repository is read only", site);
        return;
    }

    WritableContentRepository repository = (WritableContentRepository) site.getContentRepository();

    // Extract the configuration from the job properties
    String provider = (String) ctx.get(OPT_PROVIDER);
    Account account = null;
    try {
        if (StringUtils.isBlank(provider)) {
            provider = DEFAULT_PROVIDER;
        }
        account = new Account(ctx);
    } catch (IllegalArgumentException e) {
        throw new JobException(this, e);
    }

    // Connect to the server
    Properties sessionProperties = new Properties();
    Session session = Session.getDefaultInstance(sessionProperties, null);
    Store store = null;
    Folder inbox = null;

    try {

        // Connect to the server
        try {
            store = session.getStore(provider);
            store.connect(account.getHost(), account.getLogin(), account.getPassword());
        } catch (NoSuchProviderException e) {
            throw new JobException(this, "Unable to connect using unknown e-mail provider '" + provider + "'",
                    e);
        } catch (MessagingException e) {
            throw new JobException(this, "Error connecting to " + provider + " account " + account, e);
        }

        // Open the account's inbox
        try {
            inbox = store.getFolder(INBOX);
            if (inbox == null)
                throw new JobException(this, "No inbox found at " + account);
            inbox.open(Folder.READ_WRITE);
        } catch (MessagingException e) {
            throw new JobException(this, "Error connecting to inbox at " + account, e);
        }

        // Get the messages from the server
        try {
            for (Message message : inbox.getMessages()) {
                if (!message.isSet(Flag.SEEN)) {
                    try {
                        Page page = aggregate(message, site);
                        message.setFlag(Flag.DELETED, true);
                        repository.put(page, true);
                        logger.info("E-Mail message published at {}", page.getURI());
                    } catch (Exception e) {
                        logger.info("E-Mail message discarded: {}", e.getMessage());
                        message.setFlag(Flag.SEEN, true);
                        // TODO: Reply to sender if the "from" field exists
                    }
                }
            }
        } catch (MessagingException e) {
            throw new JobException(this, "Error loading e-mail messages from inbox", e);
        }

        // Close the connection
        // but don't remove the messages from the server
    } finally {
        if (inbox != null) {
            try {
                inbox.close(true);
            } catch (MessagingException e) {
                throw new JobException(this, "Error closing inbox", e);
            }
        }
        if (store != null) {
            try {
                store.close();
            } catch (MessagingException e) {
                throw new JobException(this, "Error closing connection to e-mail server", e);
            }
        }
    }

}

From source file:com.cisco.iwe.services.util.EmailMonitor.java

/**
 * This method returns the corresponding JSON response.'Success = true' in case the Mail contents get stored in the database successfully. 'Success = false' in case of any errors 
 **///ww w  .  j a v a 2s .  co m

public String monitorEmailAndLoadDB() {
    License license = new License();
    license.setLicense(EmailParseConstants.ocrLicenseFile);
    Store emailStore = null;
    Folder folder = null;
    Properties props = new Properties();
    logger.info("EmailMonitor monitorEmailAndLoadDB Enter (+)");
    // Setting session and Store information
    // MailServerConnectivity - get the email credentials based on the environment
    String[] mailCredens = getEmailCredens();
    final String username = mailCredens[0];
    final String password = mailCredens[1];
    logger.info("monitorEmailAndLoadDB : Email ID : " + username);

    try {
        logger.info("EmailMonitor.monitorEmailAndLoadDB get the mail server properties");
        props.put(EmailParseConstants.emailAuthKey, "true");
        props.put(EmailParseConstants.emailHostKey, prop.getProperty(EmailParseConstants.emailHost));
        props.put(EmailParseConstants.emailPortKey, prop.getProperty(EmailParseConstants.emailPort));
        props.put(EmailParseConstants.emailTlsKey, "true");

        logger.info("EmailMonitor.monitorEmailAndLoadDB create the session object with mail server properties");
        Session session = Session.getDefaultInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        // Prod-MailServerConnectivity - create the POP3 store object and
        // connect with the pop server
        logger.info("monitorEmailAndLoadDB : create the POP3 store object");
        emailStore = (Store) session.getStore(prop.getProperty(EmailParseConstants.emailType));
        logger.info("monitorEmailAndLoadDB : Connecting to Store :" + emailStore.toString());
        emailStore.connect(prop.getProperty(EmailParseConstants.emailHost),
                Integer.parseInt(prop.getProperty(EmailParseConstants.emailPort)), username, password);
        logger.info("monitorEmailAndLoadDB : Connection Status:" + emailStore.isConnected());

        // create the folder object
        folder = emailStore.getFolder(prop.getProperty(EmailParseConstants.emailFolder));
        // Check if Inbox exists
        if (!folder.exists()) {
            logger.error("monitorEmailAndLoadDB : No INBOX exists...");
            System.exit(0);
        }
        // Open inbox and read messages
        logger.info("monitorEmailAndLoadDB : Connected to Folder");
        folder.open(Folder.READ_WRITE);

        // retrieve the messages from the folder in an array and process it
        Message[] msgArr = folder.getMessages();
        // Read each message and delete the same once data is stored in DB
        logger.info("monitorEmailAndLoadDB : Message length::::" + msgArr.length);

        SimpleDateFormat sdf2 = new SimpleDateFormat(EmailParseConstants.dateFormat);

        Date sent = null;
        String emailContent = null;
        String contentType = null;
        // for (int i = 0; i < msg.length; i++) {
        for (int i = msgArr.length - 1; i > msgArr.length - 2; i--) {
            Message message = msgArr[i];
            if (!message.isSet(Flags.Flag.SEEN)) {
                try {
                    sent = msgArr[i].getSentDate();
                    contentType = message.getContentType();
                    String fileType = null;
                    byte[] byteArr = null;
                    String validAttachments = EmailParseConstants.validAttachmentTypes;
                    if (contentType.contains("multipart")) {
                        Multipart multiPart = (Multipart) message.getContent();
                        int numberOfParts = multiPart.getCount();
                        for (int partCount = 0; partCount < numberOfParts; partCount++) {
                            MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
                            InputStream inStream = (InputStream) part.getInputStream();
                            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                            int nRead;
                            byte[] data = new byte[16384];
                            while ((nRead = inStream.read(data, 0, data.length)) != -1) {
                                buffer.write(data, 0, nRead);
                            }
                            buffer.flush();
                            byteArr = buffer.toByteArray();
                            if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                                fileType = part.getFileName().substring(part.getFileName().lastIndexOf("."),
                                        part.getFileName().length());
                                String fileDir = part.getFileName();
                                if (validAttachments.contains(fileType)) {
                                    part.saveFile(fileDir);
                                    saveAttachmentAndText(message.getFrom()[0].toString(), message.getSubject(),
                                            byteArr, emailContent.getBytes(), fileType, sent,
                                            fileType.equalsIgnoreCase(".PDF") ? scanPDF(fileDir)
                                                    : scanImage(fileDir).toString());
                                    deleteFile(fileDir);
                                } else {
                                    sendNotification();
                                }

                            } else {
                                // this part may be the message content
                                emailContent = part.getContent().toString();
                            }
                        }
                    } else if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                        Object content = message.getContent();
                        if (content != null) {
                            emailContent = content.toString();
                        }
                    }
                    message.setFlag(Flags.Flag.DELETED, false);
                    logger.info(
                            "monitorEmailAndLoadDB : loadSuccess : Mail Parsed for : " + message.getSubject());
                    logger.info("monitorEmailAndLoadDB : loadSuccess : Created at : " + sdf2.format(sent));
                    logger.info("Message deleted");
                } catch (IOException e) {
                    logger.error("IO Exception in email monitoring: " + e);
                    logger.error(
                            "IO Exception in email monitoring message: " + Arrays.toString(e.getStackTrace()));
                } catch (SQLException sexp) {
                    logger.error("SQLException Occurred GetSpogDetails-db2 :", sexp);
                    buildErrorJson(ExceptionConstants.sqlErrCode, ExceptionConstants.sqlErrMsg);
                } catch (Exception e) {
                    logger.error("Unknown Exception in email monitoring: " + e);
                    logger.error("Unknown Exception in email monitoring message: "
                            + Arrays.toString(e.getStackTrace()));
                }
            }
        }

        // Close folder and store
        folder.close(true);
        emailStore.close();

    } catch (NoSuchProviderException e) {
        logger.error("monitorEmailAndLoadDB : NoSuchProviderException in email monitoring: " + e);
        logger.error("monitorEmailAndLoadDB : NoSuchProviderException in email monitoring message: "
                + Arrays.toString(e.getStackTrace()));
    } catch (MessagingException e) {
        logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: " + e);
        logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring message: "
                + Arrays.toString(e.getStackTrace()));
    } finally {
        if (folder != null && folder.isOpen()) {
            // Close folder and store
            try {
                folder.close(true);
                emailStore.close();
            } catch (MessagingException e) {
                logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: " + e);
                logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: "
                        + Arrays.toString(e.getStackTrace()));
            }
        }
    }
    logger.info("EmailMonitor monitorEmailAndLoadDB Exit (-)");
    return buildSuccessJson().toString();
}