Example usage for javax.mail Message getAllHeaders

List of usage examples for javax.mail Message getAllHeaders

Introduction

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

Prototype

public Enumeration<Header> getAllHeaders() throws MessagingException;

Source Link

Document

Return all the headers from this part as an Enumeration of Header objects.

Usage

From source file:com.mgmtp.jfunk.core.mail.MessageUtils.java

/**
 * Returns the specified message as text.
 * /*from  w  w  w  . j ava  2  s. c o m*/
 * @param message
 *            the message
 * @param includeHeaders
 *            specifies whether message headers are to be included in the returned text
 * @return the message text
 */
public static String messageAsText(final Message message, final boolean includeHeaders) {
    try {
        StrBuilder sb = new StrBuilder(300);

        if (includeHeaders) {
            @SuppressWarnings("unchecked")
            Enumeration<Header> headers = message.getAllHeaders();
            while (headers.hasMoreElements()) {
                Header header = headers.nextElement();
                sb.append(header.getName()).append('=').appendln(header.getValue());
            }

            sb.appendln("");
        }

        Object content = message.getContent();
        if (content instanceof String) {
            String body = (String) content;
            sb.appendln(body);
            sb.appendln("");
        } else if (content instanceof Multipart) {
            parseMultipart(sb, (Multipart) content);
        }
        return sb.toString();
    } catch (MessagingException ex) {
        throw new MailException("Error getting mail content.", ex);
    } catch (IOException ex) {
        throw new MailException("Error getting mail content.", ex);
    }
}

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

private static String formatHeader(Message thisMessage) throws Exception {
    Enumeration<Header> E = thisMessage.getAllHeaders();
    StringBuilder tmp = new StringBuilder(128);
    while (E.hasMoreElements()) {
        Header hdr = E.nextElement();/*from  w  w  w . j a va 2 s .c om*/
        tmp.append(hdr.getName());
        tmp.append(": ");
        tmp.append(hdr.getValue());
        tmp.append("\r\n");
    }

    return tmp.toString();
}

From source file:de.saly.elasticsearch.support.IndexableMailMessage.java

public static IndexableMailMessage fromJavaMailMessage(final Message jmm, final boolean withTextContent,
        final boolean withAttachments, final boolean stripTags, List<String> headersToFields)
        throws MessagingException, IOException {
    final IndexableMailMessage im = new IndexableMailMessage();

    @SuppressWarnings("unchecked")
    final Enumeration<Header> allHeaders = jmm.getAllHeaders();

    final Set<IndexableHeader> headerList = new HashSet<IndexableHeader>();
    while (allHeaders.hasMoreElements()) {
        final Header h = allHeaders.nextElement();
        headerList.add(new IndexableHeader(h.getName(), h.getValue()));
    }//from   w  ww  .j a v a 2  s . c o  m

    im.setHeaders(headerList.toArray(new IndexableHeader[headerList.size()]));

    im.setSelectedHeaders(extractHeaders(im.getHeaders(), headersToFields));

    if (jmm.getFolder() instanceof POP3Folder) {
        im.setPopId(((POP3Folder) jmm.getFolder()).getUID(jmm));
        im.setMailboxType("POP");

    } else {
        im.setMailboxType("IMAP");
    }

    if (jmm.getFolder() instanceof UIDFolder) {
        im.setUid(((UIDFolder) jmm.getFolder()).getUID(jmm));
    }

    im.setFolderFullName(jmm.getFolder().getFullName());

    im.setFolderUri(jmm.getFolder().getURLName().toString());

    im.setContentType(jmm.getContentType());
    im.setSubject(jmm.getSubject());
    im.setSize(jmm.getSize());
    im.setSentDate(jmm.getSentDate());

    if (jmm.getReceivedDate() != null) {
        im.setReceivedDate(jmm.getReceivedDate());
    }

    if (jmm.getFrom() != null && jmm.getFrom().length > 0) {
        im.setFrom(Address.fromJavaMailAddress(jmm.getFrom()[0]));
    }

    if (jmm.getRecipients(RecipientType.TO) != null) {
        im.setTo(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.TO)));
    }

    if (jmm.getRecipients(RecipientType.CC) != null) {
        im.setCc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.CC)));
    }

    if (jmm.getRecipients(RecipientType.BCC) != null) {
        im.setBcc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.BCC)));
    }

    if (withTextContent) {

        // try {

        String textContent = getText(jmm, 0);

        if (stripTags) {
            textContent = stripTags(textContent);
        }

        im.setTextContent(textContent);
        // } catch (final Exception e) {
        // logger.error("Unable to retrieve text content for message {} due to {}",
        // e, ((MimeMessage) jmm).getMessageID(), e);
        // }
    }

    if (withAttachments) {

        try {
            final Object content = jmm.getContent();

            // look for attachments
            if (jmm.isMimeType("multipart/*") && content instanceof Multipart) {
                List<ESAttachment> attachments = new ArrayList<ESAttachment>();

                final Multipart multipart = (Multipart) content;

                for (int i = 0; i < multipart.getCount(); i++) {
                    final BodyPart bodyPart = multipart.getBodyPart(i);
                    if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())
                            && !StringUtils.isNotBlank(bodyPart.getFileName())) {
                        continue; // dealing with attachments only
                    }
                    final InputStream is = bodyPart.getInputStream();
                    final byte[] bytes = IOUtils.toByteArray(is);
                    IOUtils.closeQuietly(is);
                    attachments.add(new ESAttachment(bodyPart.getContentType(), bytes, bodyPart.getFileName()));
                }

                if (!attachments.isEmpty()) {
                    im.setAttachments(attachments.toArray(new ESAttachment[attachments.size()]));
                    im.setAttachmentCount(im.getAttachments().length);
                    attachments.clear();
                    attachments = null;
                }

            }
        } catch (final Exception e) {
            logger.error(
                    "Error indexing attachments (message will be indexed but without attachments) due to {}", e,
                    e.toString());
        }

    }

    im.setFlags(IMAPUtils.toStringArray(jmm.getFlags()));
    im.setFlaghashcode(jmm.getFlags().hashCode());

    return im;
}

From source file:com.canoo.webtest.plugins.emailtest.EmailMessageStructureFilter.java

private void processHeaders(final StringBuffer buf, final Message message) throws MessagingException {
    if (fTokenizedHeaders != null) {
        final Enumeration allHeaders = message.getAllHeaders();
        while (allHeaders.hasMoreElements()) {
            final Header header = (Header) allHeaders.nextElement();
            if (headerIsRequired(header)) {
                buf.append(processHeader(header));
            }//from   ww  w .j  a v a  2s .  c  om
        }
    }
}

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

/**
 * @param msg/*from  www  .  j a va 2s  . c o  m*/
 * @return
 */
@SuppressWarnings("unchecked")
private String generateHeader(Message msg) {

    StringBuffer headerString = new StringBuffer();

    try {
        Enumeration<Header> e = msg.getAllHeaders();
        if (e != null) {
            for (; e.hasMoreElements();) {
                Header header = e.nextElement();
                headerString.append(header.getName());
                headerString.append(": ");
                headerString.append(header.getValue());
                headerString.append('\n');
            }
        }
    } catch (MessagingException e) {
        logger.error(e.getMessage(), e);
    }

    return headerString.toString();
}

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

/**
 * @param msg//from  w w  w. j  a  v a  2s . c o m
 * @return
 */
@SuppressWarnings("unchecked")
private String generateHeader(Message msg) {

    StringBuffer headerString = new StringBuffer();

    try {
        Enumeration<Header> e = msg.getAllHeaders();
        if (e != null) {
            for (; e.hasMoreElements();) {
                Header header = e.nextElement();
                headerString.append(header.getName());
                headerString.append(": ");
                headerString.append(header.getValue());
                headerString.append('\n');
            }
        }
    } catch (MessagingException e) {
        log.error(e.getMessage(), e);
    }

    return headerString.toString();
}

From source file:de.saly.elasticsearch.importer.imap.support.IndexableMailMessage.java

public static IndexableMailMessage fromJavaMailMessage(final Message jmm, final boolean withTextContent,
        final boolean withHtmlContent, final boolean preferHtmlContent, final boolean withAttachments,
        final boolean stripTags, List<String> headersToFields) throws MessagingException, IOException {
    final IndexableMailMessage im = new IndexableMailMessage();

    @SuppressWarnings("unchecked")
    final Enumeration<Header> allHeaders = jmm.getAllHeaders();

    final Set<IndexableHeader> headerList = new HashSet<IndexableHeader>();
    while (allHeaders.hasMoreElements()) {
        final Header h = allHeaders.nextElement();
        headerList.add(new IndexableHeader(h.getName(), h.getValue()));
    }/*w w  w  .  j a va  2 s. c  o m*/

    im.setHeaders(headerList.toArray(new IndexableHeader[headerList.size()]));

    im.setSelectedHeaders(extractHeaders(im.getHeaders(), headersToFields));

    if (jmm.getFolder() instanceof POP3Folder) {
        im.setPopId(((POP3Folder) jmm.getFolder()).getUID(jmm));
        im.setMailboxType("POP");

    } else {
        im.setMailboxType("IMAP");
    }

    if (jmm.getFolder() instanceof UIDFolder) {
        im.setUid(((UIDFolder) jmm.getFolder()).getUID(jmm));
    }

    im.setFolderFullName(jmm.getFolder().getFullName());

    im.setFolderUri(jmm.getFolder().getURLName().toString());

    im.setContentType(jmm.getContentType());
    im.setSubject(jmm.getSubject());
    im.setSize(jmm.getSize());
    im.setSentDate(jmm.getSentDate());

    if (jmm.getReceivedDate() != null) {
        im.setReceivedDate(jmm.getReceivedDate());
    }

    if (jmm.getFrom() != null && jmm.getFrom().length > 0) {
        im.setFrom(Address.fromJavaMailAddress(jmm.getFrom()[0]));
    }

    if (jmm.getRecipients(RecipientType.TO) != null) {
        im.setTo(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.TO)));
    }

    if (jmm.getRecipients(RecipientType.CC) != null) {
        im.setCc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.CC)));
    }

    if (jmm.getRecipients(RecipientType.BCC) != null) {
        im.setBcc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.BCC)));
    }

    if (withTextContent) {

        // try {

        String textContent = getText(jmm, 0, preferHtmlContent);

        if (stripTags) {
            textContent = stripTags(textContent);
        }

        im.setTextContent(textContent);
        // } catch (final Exception e) {
        // logger.error("Unable to retrieve text content for message {} due to {}",
        // e, ((MimeMessage) jmm).getMessageID(), e);
        // }
    }

    if (withHtmlContent) {

        // try {

        String htmlContent = getText(jmm, 0, true);

        im.setHtmlContent(htmlContent);
        // } catch (final Exception e) {
        // logger.error("Unable to retrieve text content for message {} due to {}",
        // e, ((MimeMessage) jmm).getMessageID(), e);
        // }
    }

    if (withAttachments) {

        try {
            final Object content = jmm.getContent();

            // look for attachments
            if (jmm.isMimeType("multipart/*") && content instanceof Multipart) {
                List<ESAttachment> attachments = new ArrayList<ESAttachment>();

                final Multipart multipart = (Multipart) content;

                for (int i = 0; i < multipart.getCount(); i++) {
                    final BodyPart bodyPart = multipart.getBodyPart(i);
                    if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())
                            && !StringUtils.isNotBlank(bodyPart.getFileName())) {
                        continue; // dealing with attachments only
                    }
                    final InputStream is = bodyPart.getInputStream();
                    final byte[] bytes = IOUtils.toByteArray(is);
                    IOUtils.closeQuietly(is);
                    attachments.add(new ESAttachment(bodyPart.getContentType(), bytes, bodyPart.getFileName()));
                }

                if (!attachments.isEmpty()) {
                    im.setAttachments(attachments.toArray(new ESAttachment[attachments.size()]));
                    im.setAttachmentCount(im.getAttachments().length);
                    attachments.clear();
                    attachments = null;
                }

            }
        } catch (final Exception e) {
            logger.error(
                    "Error indexing attachments (message will be indexed but without attachments) due to {}", e,
                    e.toString());
        }

    }

    im.setFlags(IMAPUtils.toStringArray(jmm.getFlags()));
    im.setFlaghashcode(jmm.getFlags().hashCode());

    return im;
}

From source file:com.jlgranda.fede.ejb.mail.reader.EmailHelper.java

/**
 * get the full Mail from a message/*  w ww.j  a v a  2 s. c o m*/
 * 
 * @param message
 * @return
 * @throws MessagingException
 * @throws IOException
 */
public String fullMail(javax.mail.Message message) throws MessagingException, IOException {
    StringBuffer sBuf = new StringBuffer();
    @SuppressWarnings("unchecked")
    Enumeration<javax.mail.Header> headers = message.getAllHeaders();
    while (headers.hasMoreElements()) {
        javax.mail.Header header = headers.nextElement();
        sBuf.append(header.getName()).append(": ").append(header.getValue()).append("\n");
    }
    sBuf.append(fromInputStream(message.getInputStream()));
    return sBuf.toString();
}

From source file:es.ucm.fdi.dalgs.mailbox.service.MailBoxService.java

private ResultClass<Boolean> parseSubjectAndCreate(MessageBox messageBox, Message msg)
        throws MessagingException, IOException {

    ResultClass<Boolean> result = new ResultClass<>();

    Pattern p = Pattern.compile(pattern);
    Matcher m = p.matcher(messageBox.getSubject());
    if (m.matches()) {

        String mimeType = msg.getAllHeaders() + msg.getContentType();
        String key = getStorageKey(Long.parseLong(m.group(3)));

        storageManager.putObject(bucket, key, mimeType, msg.getInputStream());
        String aaa = storageManager.getUrl(bucket, key).toExternalForm();
        messageBox.setFile(aaa);/*from w  w w  .ja  v  a  2 s.co  m*/

        if (("group").equalsIgnoreCase(m.group(2))) {
            Group group = serviceGroup.getGroupFormatter(Long.parseLong(m.group(3)));
            if (group != null) {
                group.getMessages().add(messageBox);
                result = serviceGroup.updateGroup(group);
            }

        }

        else if (("course").equalsIgnoreCase(m.group(2))) {
            Course course = serviceCourse.getCourseFormatter(Long.parseLong(m.group(3)));
            if (course != null) {
                course.getMessages().add(messageBox);
                result = serviceCourse.updateCourse(course);
            }
        }

    }
    return result;
}

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

private boolean extractMessage(Message Mess, long messageID, String attachURI, String attachDIR) {
    cfArrayData ADD = cfArrayData.createArray(1);

    try {/*from w ww . j  a va  2 s  .  c  o  m*/

        setData("subject", new cfStringData(Mess.getSubject()));
        setData("id", new cfNumberData(messageID));

        //--- Pull out all the headers
        cfStructData headers = new cfStructData();
        Enumeration<Header> eH = Mess.getAllHeaders();
        String headerKey;
        while (eH.hasMoreElements()) {
            Header hdr = eH.nextElement();

            headerKey = hdr.getName().replace('-', '_').toLowerCase();
            if (headers.containsKey(headerKey)) {
                headers.setData(headerKey,
                        new cfStringData(headers.getData(headerKey).toString() + ";" + hdr.getValue()));
            } else
                headers.setData(headerKey, new cfStringData(hdr.getValue()));
        }

        setData("headers", headers);

        // Get the Date
        Date DD = Mess.getReceivedDate();
        if (DD == null)
            setData("rxddate", new cfDateData(System.currentTimeMillis()));
        else
            setData("rxddate", new cfDateData(DD.getTime()));

        DD = Mess.getSentDate();
        if (DD == null)
            setData("sentdate", new cfDateData(System.currentTimeMillis()));
        else
            setData("sentdate", new cfDateData(DD.getTime()));

        // Get the FROM field
        Address[] from = Mess.getFrom();
        if (from != null && from.length > 0) {
            cfStructData sdFrom = new cfStructData();
            String name = ((InternetAddress) from[0]).getPersonal();
            if (name != null)
                sdFrom.setData("name", new cfStringData(name));

            sdFrom.setData("email", new cfStringData(((InternetAddress) from[0]).getAddress()));
            setData("from", sdFrom);
        }

        //--[ Get the TO/CC/BCC field
        cfArrayData AD = extractAddresses(Mess.getRecipients(Message.RecipientType.TO));
        if (AD != null)
            setData("to", AD);

        AD = extractAddresses(Mess.getRecipients(Message.RecipientType.CC));
        if (AD != null)
            setData("cc", AD);

        AD = extractAddresses(Mess.getRecipients(Message.RecipientType.BCC));
        if (AD != null)
            setData("bcc", AD);

        AD = extractAddresses(Mess.getReplyTo());
        if (AD != null)
            setData("replyto", AD);

        //--[ Set the flags
        setData("answered", cfBooleanData.getcfBooleanData(Mess.isSet(Flags.Flag.ANSWERED)));
        setData("deleted", cfBooleanData.getcfBooleanData(Mess.isSet(Flags.Flag.DELETED)));
        setData("draft", cfBooleanData.getcfBooleanData(Mess.isSet(Flags.Flag.DRAFT)));
        setData("flagged", cfBooleanData.getcfBooleanData(Mess.isSet(Flags.Flag.FLAGGED)));
        setData("recent", cfBooleanData.getcfBooleanData(Mess.isSet(Flags.Flag.RECENT)));
        setData("seen", cfBooleanData.getcfBooleanData(Mess.isSet(Flags.Flag.SEEN)));

        setData("size", new cfNumberData(Mess.getSize()));
        setData("lines", new cfNumberData(Mess.getLineCount()));

        String tmp = Mess.getContentType();
        if (tmp.indexOf(";") != -1)
            tmp = tmp.substring(0, tmp.indexOf(";"));

        setData("mimetype", new cfStringData(tmp));

        // Get the body of the email
        extractBody(Mess, ADD, attachURI, attachDIR);

    } catch (Exception E) {
        return false;
    }

    setData("body", ADD);
    return true;
}