Example usage for javax.mail.internet MimeMessage getAllHeaders

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

Introduction

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

Prototype

@Override
public Enumeration<Header> getAllHeaders() throws MessagingException 

Source Link

Document

Return all the headers from this Message as an enumeration of Header objects.

Usage

From source file:com.stimulus.archiva.domain.EmailID.java

public static synchronized String generateUniqueID(Email email) {
    try {/*from   www.  ja va  2 s . c o m*/
        MimeMessage raw = email;
        // we need a backup plan here
        if (raw == null) {
            return DateUtil.convertDatetoString(new Date());
        }
        Enumeration<Header> headers = raw.getAllHeaders();
        LinkedList<String> orderedHeaders = new LinkedList<String>();
        while (headers.hasMoreElements()) {
            Header header = headers.nextElement();

            if (Compare.equalsIgnoreCase(header.getName(), "Date")
                    || Compare.equalsIgnoreCase(header.getName(), "CC")
                    || Compare.equalsIgnoreCase(header.getName(), "BCC")
                    || Compare.equalsIgnoreCase(header.getName(), "Subject")
                    || Compare.equalsIgnoreCase(header.getName(), "To")
                    || Compare.equalsIgnoreCase(header.getName(), "From"))
                orderedHeaders.add(header.getName() + header.getValue());

        }
        Collections.sort(orderedHeaders);
        StringBuffer allHeaders = new StringBuffer();
        for (String header : orderedHeaders)
            allHeaders.append(header);
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        byte[] bytes = allHeaders.toString().getBytes();
        InputStream is = new ByteArrayInputStream(bytes);
        DigestInputStream dis = new DigestInputStream(is, sha);
        while (dis.read() != -1)
            ;
        dis.close();
        byte[] digest = sha.digest();
        return toHex(digest);
    } catch (Exception e) {
        logger.error("failed to generate a uniqueid for a message");
        return null;
    }
}

From source file:mitm.common.mail.BodyPartUtils.java

/**
 * This is the only way I know of to create a new MimeBodyPart from another Message which is safe
 * for signed email. All other methods break the signature when quoted printable soft breaks are used.
 * //from  w  w w.  j  av a  2 s  . c  om
 * example of quoted printable soft breaks:
 * 
 * Content-Transfer-Encoding: quoted-printable
        
 * soft break example =
 * another line =
 *
 * All other methods will re-encode and removes the soft breaks.
 * 
 * @param sourceMessage
 * @param matcher
 * @return
 * @throws IOException
 * @throws MessagingException
 */
@SuppressWarnings("unchecked")
public static MimeBodyPart makeContentBodyPartRawBytes(MimeMessage sourceMessage, HeaderMatcher matcher)
        throws IOException, MessagingException {
    /*
     * getRawInputStream() can throw a MessagingException when the source message is a MimeMessage
     * that is created in code (ie. not from a stream)
     */
    InputStream messageStream = sourceMessage.getRawInputStream();

    byte[] rawMessage = IOUtils.toByteArray(messageStream);

    InternetHeaders destinationHeaders = new InternetHeaders();

    Enumeration<Header> sourceHeaders = sourceMessage.getAllHeaders();

    HeaderUtils.copyHeaders(sourceHeaders, destinationHeaders, matcher);

    MimeBodyPart newBodyPart = new MimeBodyPart(destinationHeaders, rawMessage);

    return newBodyPart;
}

From source file:me.normanmaurer.camel.smtp.SMTPTest.java

@SuppressWarnings("unchecked")
@Test/* w w  w  . j  a  v  a2  s.co  m*/
public void testSendMatchingMessage() throws Exception {
    String sender = "sender@localhost";
    String rcpt = "rcpt@localhost";
    String body = "Subject: test\r\n\r\nTestmail";
    SMTPClient client = new SMTPClient();
    client.connect("localhost", 2525);
    client.helo("localhost");
    client.setSender(sender);
    client.addRecipient(rcpt);

    client.sendShortMessageData(body);
    client.quit();
    client.disconnect();
    resultEndpoint.expectedMessageCount(1);
    resultEndpoint.expectedBodyReceived().body(InputStream.class);
    Exchange ex = resultEndpoint.getReceivedExchanges().get(0);
    Map<String, Object> headers = ex.getIn().getHeaders();
    assertEquals(sender, headers.get(MailEnvelopeMessage.SMTP_SENDER_ADRRESS));
    assertEquals(rcpt, headers.get(MailEnvelopeMessage.SMTP_RCPT_ADRRESS_LIST));

    // check type converter
    MimeMessage message = ex.getIn().getBody(MimeMessage.class);
    Enumeration<Header> mHeaders = message.getAllHeaders();
    Header header = null;
    while (mHeaders.hasMoreElements()) {
        header = mHeaders.nextElement();
        if (header.getName().equals("Subject")) {
            break;
        }
    }
    assertNotNull(header);
    assertEquals("Subject", header.getName());
    assertEquals(header.getValue(), "test");

    resultEndpoint.assertIsSatisfied();
}

From source file:com.adaptris.core.mail.MetadataMailHeaders.java

@Override
public void handle(MimeMessage mime, AdaptrisMessage msg) throws MessagingException {
    Set<MetadataElement> metadata = new HashSet<MetadataElement>();
    Enumeration headers = mime.getAllHeaders();
    String pfx = StringUtils.defaultIfBlank(getPrefix(), "");
    while (headers.hasMoreElements()) {
        Header h = (Header) headers.nextElement();
        metadata.add(new MetadataElement(pfx + h.getName(), h.getValue()));
    }// www .  j  a  v a  2s.co m
    msg.setMetadata(filter().filter(metadata).toSet());
}

From source file:com.spartasystems.holdmail.smtp.SMTPHandler.java

protected MessageHeaders getHeaders(MimeMessage message) throws MessagingException {

    Map<String, String> headerMap = new HashMap<>();

    // oh wow 2015 and it's untyped and uses Enumeration
    Enumeration allHeaders = message.getAllHeaders();
    while (allHeaders.hasMoreElements()) {
        Header header = (Header) allHeaders.nextElement();
        String headerName = header.getName();
        String headerVal = header.getValue();

        headerMap.put(headerName, headerVal);

    }//  ww  w .  j a v a  2s .c o  m

    return new MessageHeaders(headerMap);
}

From source file:eu.openanalytics.rsb.component.EmailDepositHandler.java

@SuppressWarnings("unchecked")
public void handleJob(final Message<MimeMessage> message) throws MessagingException, IOException {
    final DepositEmailConfiguration depositEmailConfiguration = message.getHeaders()
            .get(EMAIL_CONFIG_HEADER_NAME, DepositEmailConfiguration.class);
    final String applicationName = depositEmailConfiguration.getApplicationName();
    final MimeMessage mimeMessage = message.getPayload();

    final Address[] replyTo = mimeMessage.getReplyTo();
    Validate.notEmpty(replyTo, "no reply address found for job emailed with headers:"
            + Collections.list(mimeMessage.getAllHeaders()));

    final Map<String, Serializable> meta = new HashMap<String, Serializable>();
    meta.put(EMAIL_SUBJECT_META_NAME, mimeMessage.getSubject());
    meta.put(EMAIL_ADDRESSEE_META_NAME, getPrimaryAddressee(mimeMessage));
    meta.put(EMAIL_REPLY_TO_META_NAME, replyTo[0].toString());
    meta.put(EMAIL_REPLY_CC_META_NAME, getCCAddressees(mimeMessage));
    meta.put(EMAIL_BODY_META_NAME, getResponseBody(depositEmailConfiguration));

    final MultiFilesJob job = new MultiFilesJob(Source.EMAIL, applicationName,
            ApplicationPermissionEvaluator.NO_AUTHENTICATED_USERNAME, UUID.randomUUID(),
            (GregorianCalendar) GregorianCalendar.getInstance(), meta);

    try {/*  ww w.ja  v  a 2s. c  o  m*/
        addEmailAttachmentsToJob(depositEmailConfiguration, mimeMessage, job);
        getMessageDispatcher().dispatch(job);
    } catch (final Exception e) {
        final MultiFilesResult errorResult = job.buildErrorResult(e, getMessages());
        handleResult(errorResult);
    }
}

From source file:mitm.common.dlp.impl.MimeMessageTextExtractorImpl.java

private void extractMimeMessageMetaInfo(MimeMessage message, PartContext context) throws MessagingException {
    TextExtractorContext extractorContext = new TextExtractorContextImpl();

    extractorContext.setEncoding(CharEncoding.US_ASCII);
    extractorContext.setName("headers");

    StrBuilder sb = new StrBuilder(4096);

    try {//  w w  w.  ja v  a 2s.  c o  m
        for (Enumeration<?> headerEnum = message.getAllHeaders(); headerEnum.hasMoreElements();) {
            Header header = (Header) headerEnum.nextElement();

            if (header == null) {
                continue;
            }

            if (skipHeaders != null && skipHeaders.contains(StringUtils.lowerCase(header.getName()))) {
                continue;
            }

            sb.append(header.getName()).append(": ").appendln(HeaderUtils.decodeTextQuietly(header.getValue()));
        }
    } catch (MessagingException e) {
        /*
         * Fallback to raw headers
         */
        for (Enumeration<?> headerEnum = message.getAllHeaderLines(); headerEnum.hasMoreElements();) {
            sb.appendln(headerEnum.nextElement());
        }
    }

    byte[] headerBytes = MiscStringUtils.toUTF8Bytes(sb.toString());

    RewindableInputStream input = new RewindableInputStream(new ByteArrayInputStream(headerBytes),
            MEM_THRESHOLD);

    ExtractedPart part = new ExtractedPartImpl(extractorContext, input, headerBytes.length);

    try {
        context.update(part, true /* add */);
    } catch (IOException e) {
        throw new MessagingException("Error adding part to context.", e);
    }
}

From source file:info.jtrac.mail.MailSender.java

/**
 * we bend the rules a little and fire off a new thread for sending
 * an email message.  This has the advantage of not slowing down the item
 * create and update screens, i.e. the system returns the next screen
 * after "submit" without blocking.  This has been used in production
 * (and now I guess in many JTrac installations worldwide)
 * for quite a while now, on Tomcat without any problems.  This helps a lot
 * especially when the SMTP server is slow to respond, etc.
 *//*from w  w  w.  j  a  va  2 s  .co m*/
private void sendInNewThread(final MimeMessage message) {
    new Thread() {
        @Override
        public void run() {
            logger.debug("send mail thread start");
            try {
                try {
                    sender.send(message);
                    logger.debug("send mail thread successfull");
                } catch (Exception e) {
                    logger.error("send mail thread failed", e);
                    logger.error("mail headers dump start");
                    Enumeration headers = message.getAllHeaders();
                    while (headers.hasMoreElements()) {
                        Header h = (Header) headers.nextElement();
                        logger.info(h.getName() + ": " + h.getValue());
                    }
                    logger.error("mail headers dump end");
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }.start();
}

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

protected void printMessageInfo(MimeMessage msg) throws Exception {
    MessageParser mp = new MessageParser(msg);
    logger.debug("Got Message :- " + msg.getSubject());
    logger.trace("With ID: " + mp.getMessageId());
    Enumeration e = msg.getAllHeaders();
    while (e.hasMoreElements()) {
        Header h = (Header) e.nextElement();
        logger.trace("HeaderLine " + h.getName() + ": " + h.getValue());
    }/*from ww w.  j av  a 2s . c om*/
    if (mp.hasAttachments()) {
        while (mp.hasMoreAttachments()) {
            Attachment a = mp.nextAttachment();
            logger.trace("Contains Attachment : " + a);
        }
    }
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * DOCUMENT ME!//from  w  w  w .  ja v a2  s  .co m
 *
 * @param message DOCUMENT ME!
 *
 * @throws javax.mail.MessagingException DOCUMENT ME!
 */
public static void clearAllHeaders(MimeMessage message) throws javax.mail.MessagingException {
    Enumeration headers = message.getAllHeaders();

    while (headers.hasMoreElements()) {
        Header header = (Header) headers.nextElement();

        try {
            message.removeHeader(header.getName());
        } catch (javax.mail.MessagingException me) {
        }
    }

    message.saveChanges();
}