Example usage for javax.mail.internet MimeMessage getMessageID

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

Introduction

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

Prototype

public String getMessageID() throws MessagingException 

Source Link

Document

Returns the value of the "Message-ID" header field.

Usage

From source file:mitm.application.djigzo.james.mailets.SMIMEHandlerTest.java

@Test
public void testNewMessageID() throws Exception {
    SMIMEHandler mailet = new SMIMEHandler();

    mailetConfig.setInitParameter("handledProcessor", "handled");
    mailetConfig.setInitParameter("retainMessageID", "false");

    mailet.init(mailetConfig);/* ww  w.j  a  v a2  s .  c o  m*/

    MockMail mail = new MockMail();

    MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/signed-encrypt-validcertificate.eml"));

    assertEquals("<602167900.17.1194204767299.JavaMail.martijn@ubuntu>", message.getMessageID());

    mail.setMessage(message);

    Set<MailAddress> recipients = new HashSet<MailAddress>();

    recipients.add(new MailAddress("m.brinkers@pobox.com"));

    mail.setRecipients(recipients);

    mail.setSender(new MailAddress("test@example.com"));

    mailet.service(mail);

    assertEquals(1, sendMailEventListener.getMails().size());

    Mail newMail = sendMailEventListener.getMails().get(0);

    SMIMEInspector inspector = new SMIMEInspectorImpl(newMail.getMessage(), null, "BC");

    assertEquals(SMIMEType.SIGNED, inspector.getSMIMEType());

    assertFalse(
            "<602167900.17.1194204767299.JavaMail.martijn@ubuntu>".equals(newMail.getMessage().getMessageID()));

    assertEquals(Mail.GHOST, mail.getState());
}

From source file:mitm.application.djigzo.james.mailets.SMIMEHandlerTest.java

@Test
public void testDefaultSettings() throws Exception {
    SMIMEHandler mailet = new SMIMEHandler();

    mailetConfig.setInitParameter("handledProcessor", "handled");

    mailet.init(mailetConfig);//w w w  . ja va2s. co m

    MockMail mail = new MockMail();

    MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/signed-encrypt-validcertificate.eml"));

    assertEquals("<602167900.17.1194204767299.JavaMail.martijn@ubuntu>", message.getMessageID());

    mail.setMessage(message);

    Set<MailAddress> recipients = new HashSet<MailAddress>();

    recipients.add(new MailAddress("m.brinkers@pobox.com"));

    mail.setRecipients(recipients);

    mail.setSender(new MailAddress("test@example.com"));

    assertEquals(22, proxy.getKeyAndCertStoreSize());

    mailet.service(mail);

    assertEquals(1, sendMailEventListener.getMails().size());

    Mail newMail = sendMailEventListener.getMails().get(0);

    SMIMEInspector inspector = new SMIMEInspectorImpl(newMail.getMessage(), null, "BC");

    assertEquals(SMIMEType.SIGNED, inspector.getSMIMEType());

    assertEquals("<602167900.17.1194204767299.JavaMail.martijn@ubuntu>", newMail.getMessage().getMessageID());

    assertEquals(Mail.GHOST, mail.getState());

    /*
     * certs should have been added
     */
    assertEquals(25, proxy.getKeyAndCertStoreSize());
}

From source file:mitm.application.djigzo.james.mailets.SMIMEHandlerTest.java

@Test
public void testRemoveSignature() throws Exception {
    SMIMEHandler mailet = new SMIMEHandler();

    mailetConfig.setInitParameter("removeSignature", "true");
    mailetConfig.setInitParameter("handledProcessor", "handled");

    mailet.init(mailetConfig);// w w w.j av a  2  s  .  c om

    MockMail mail = new MockMail();

    MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/signed-encrypt-validcertificate.eml"));

    assertEquals("<602167900.17.1194204767299.JavaMail.martijn@ubuntu>", message.getMessageID());

    mail.setMessage(message);

    SMIMEInspector inspector = new SMIMEInspectorImpl(mail.getMessage(), null, "BC");

    assertEquals(SMIMEType.ENCRYPTED, inspector.getSMIMEType());

    Set<MailAddress> recipients = new HashSet<MailAddress>();

    recipients.add(new MailAddress("m.brinkers@pobox.com"));

    mail.setRecipients(recipients);

    mail.setSender(new MailAddress("test@example.com"));

    mailet.service(mail);

    assertEquals(1, sendMailEventListener.getMails().size());

    Mail newMail = sendMailEventListener.getMails().get(0);

    assertEquals("handled", newMail.getState());

    inspector = new SMIMEInspectorImpl(newMail.getMessage(), null, "BC");

    assertEquals(SMIMEType.NONE, inspector.getSMIMEType());

    assertEquals("<602167900.17.1194204767299.JavaMail.martijn@ubuntu>", newMail.getMessage().getMessageID());

    assertEquals(Mail.GHOST, mail.getState());
}

From source file:mitm.application.djigzo.james.mailets.SMIMEHandlerTest.java

@Test
public void testRemoveSignatureMailAttribute() throws Exception {
    SMIMEHandler mailet = new SMIMEHandler();

    mailetConfig.setInitParameter("handledProcessor", "handled");
    mailetConfig.setInitParameter("removeSignatureAttribute", "attr.removeSignature");

    mailet.init(mailetConfig);//from   ww w  .j  av a2s  .c o  m

    MockMail mail = new MockMail();

    MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/signed-encrypt-validcertificate.eml"));

    assertEquals("<602167900.17.1194204767299.JavaMail.martijn@ubuntu>", message.getMessageID());

    mail.setMessage(message);
    mail.setAttribute("attr.removeSignature", "true");

    SMIMEInspector inspector = new SMIMEInspectorImpl(mail.getMessage(), null, "BC");

    assertEquals(SMIMEType.ENCRYPTED, inspector.getSMIMEType());

    Set<MailAddress> recipients = new HashSet<MailAddress>();

    recipients.add(new MailAddress("m.brinkers@pobox.com"));

    mail.setRecipients(recipients);

    mail.setSender(new MailAddress("test@example.com"));

    mailet.service(mail);

    assertEquals(1, sendMailEventListener.getMails().size());

    Mail newMail = sendMailEventListener.getMails().get(0);

    assertEquals("handled", newMail.getState());

    inspector = new SMIMEInspectorImpl(newMail.getMessage(), null, "BC");

    assertEquals(SMIMEType.NONE, inspector.getSMIMEType());

    assertEquals("<602167900.17.1194204767299.JavaMail.martijn@ubuntu>", newMail.getMessage().getMessageID());

    assertEquals(Mail.GHOST, mail.getState());
}

From source file:org.apache.solr.handler.dataimport.FsMailEntityProcessor.java

private boolean addEnvelopToDocument(Part part, Map<String, Object> row) throws MessagingException {
    MimeMessage mail = (MimeMessage) part;
    Address[] adresses;//  w ww .j a  va 2  s  . c om
    if ((adresses = mail.getFrom()) != null && adresses.length > 0) {
        String from = adresses[0].toString();
        // check if we should ignore this sender
        for (String ignore : this.ignoreFrom) {
            if (from.toLowerCase().contains(ignore)) {
                LOG.info("Ignoring email from " + from);
                return false;
            }
        }
        row.put(FROM, from);
        row.put(FROM_CLEAN, cleanAddress(from));
    } else {
        return false;
    }

    List<String> to = new ArrayList<String>();
    if ((adresses = mail.getRecipients(Message.RecipientType.TO)) != null) {
        addAddressToList(adresses, to);
    }
    if ((adresses = mail.getRecipients(Message.RecipientType.CC)) != null) {
        addAddressToList(adresses, to);
    }
    if ((adresses = mail.getRecipients(Message.RecipientType.BCC)) != null) {
        addAddressToList(adresses, to);
    }
    if (!to.isEmpty()) {
        row.put(TO_CC_BCC, to);
        List<String> cleanAddresses = cleanAddresses(to);
        row.put(TO_CC_BCC_CLEAN, cleanAddresses);
        // save first TO address into separate field
        row.put(TO, to.get(0));
        row.put(TO_CLEAN, cleanAddresses.get(0));
    }

    row.put(MESSAGE_ID, mail.getMessageID());
    row.put(SUBJECT, mail.getSubject());

    {
        Date d = mail.getSentDate();
        if (d != null) {
            row.put(SENT_DATE, d);
        }
    }
    {
        Date d = mail.getReceivedDate();
        if (d != null) {
            row.put(RECEIVED_DATE, d);
        }
    }

    List<String> flags = new ArrayList<String>();
    for (Flags.Flag flag : mail.getFlags().getSystemFlags()) {
        if (flag == Flags.Flag.ANSWERED) {
            flags.add(FLAG_ANSWERED);
        } else if (flag == Flags.Flag.DELETED) {
            flags.add(FLAG_DELETED);
        } else if (flag == Flags.Flag.DRAFT) {
            flags.add(FLAG_DRAFT);
        } else if (flag == Flags.Flag.FLAGGED) {
            flags.add(FLAG_FLAGGED);
        } else if (flag == Flags.Flag.RECENT) {
            flags.add(FLAG_RECENT);
        } else if (flag == Flags.Flag.SEEN) {
            flags.add(FLAG_SEEN);
        }
    }
    flags.addAll(Arrays.asList(mail.getFlags().getUserFlags()));
    row.put(FLAGS, flags);

    String[] hdrs = mail.getHeader("X-Mailer");
    if (hdrs != null) {
        row.put(XMAILER, hdrs[0]);
    }
    return true;
}

From source file:mitm.application.djigzo.james.mailets.SMIMEHandlerTest.java

@Test
public void testDecryptOL2010WithMissingSKIInSubjectWorkaroundEnabled() throws Exception {
    boolean skiWorkaroundEnabled = SecurityConstants.isOutlook2010SKIWorkaroundEnabled();

    try {/*www. j a  v a2s  .co  m*/
        SecurityConstants.setOutlook2010SKIWorkaroundEnabled(true);

        importKeyStore(keyAndCertificateWorkflow,
                new File("test/resources/testdata/keys/outlook2010_cert_missing_subjkeyid.p12"), "");

        SMIMEHandler mailet = new SMIMEHandler();

        mailetConfig.setInitParameter("handledProcessor", "handled");

        mailet.init(mailetConfig);

        MockMail mail = new MockMail();

        MimeMessage message = MailUtils
                .loadMessage(new File(testBase, "mail/outlook2010_cert_missing_subjkeyid.eml"));

        mail.setMessage(message);

        Set<MailAddress> recipients = new HashSet<MailAddress>();

        recipients.add(new MailAddress("m.brinkers@pobox.com"));

        mail.setRecipients(recipients);

        mail.setSender(new MailAddress("test@example.com"));

        mailet.service(mail);

        assertEquals(1, sendMailEventListener.getMails().size());

        Mail newMail = sendMailEventListener.getMails().get(0);

        MimeMessage decrypted = newMail.getMessage();

        assertTrue(decrypted.isMimeType("text/plain"));
        assertEquals("A broken S/MIME encrypted message", decrypted.getSubject());
        assertEquals("<000c01cadd1e$d8e3b700$8aab2500$@Domain>", decrypted.getMessageID());
        assertEquals(message.getMessageID(), decrypted.getMessageID());
        assertEquals("3DES, Key size: 168", decrypted.getHeader("X-Djigzo-Info-Encryption-Algorithm-0", ","));
        assertEquals("//2219E504D5750B37D20CC930B14129E1A2E583B1/1.2.840.113549.1.1.1",
                decrypted.getHeader("X-Djigzo-Info-Encryption-Recipient-0-0", ","));
        assertEquals("Created with Outlook 2010 Beta (14.0.4536.1000)",
                StringUtils.trim((String) decrypted.getContent()));

        assertEquals(Mail.GHOST, mail.getState());
    } finally {
        SecurityConstants.setOutlook2010SKIWorkaroundEnabled(skiWorkaroundEnabled);
    }
}

From source file:org.apache.solr.handler.dataimport.GmailServiceUserMailEntityProcessor.java

private boolean addEnvelopToDocument(Part part, Map<String, Object> row) throws MessagingException {
    MimeMessage mail = (MimeMessage) part;
    Address[] adresses;//  w  ww. j a  va  2  s .  c  o m
    if ((adresses = mail.getFrom()) != null && adresses.length > 0) {
        String from = adresses[0].toString();
        // check if we should ignore this sender
        for (String ignore : this.ignoreFrom) {
            if (from.toLowerCase().contains(ignore)) {
                LOG.info("Ignoring email from " + from);
                return false;
            }
        }
        row.put(FROM, from);
        row.put(FROM_CLEAN, cleanAddress(from));
    } else {
        return false;
    }

    List<String> to = new ArrayList<String>();
    if ((adresses = mail.getRecipients(Message.RecipientType.TO)) != null) {
        addAddressToList(adresses, to);
    }
    if ((adresses = mail.getRecipients(Message.RecipientType.CC)) != null) {
        addAddressToList(adresses, to);
    }
    if ((adresses = mail.getRecipients(Message.RecipientType.BCC)) != null) {
        addAddressToList(adresses, to);
    }
    if (!to.isEmpty()) {
        row.put(TO_CC_BCC, to);
        List<String> cleanAddresses = cleanAddresses(to);
        row.put(TO_CC_BCC_CLEAN, cleanAddresses);

        // save first TO address into separate field
        row.put(TO, to.get(0));
        row.put(TO_CLEAN, cleanAddresses.get(0));
    }

    row.put(MESSAGE_ID, mail.getMessageID());
    row.put(SUBJECT, mail.getSubject());

    {
        Date d = mail.getSentDate();
        if (d != null) {
            row.put(SENT_DATE, d);
        }
    }
    {
        Date d = mail.getReceivedDate();
        if (d != null) {
            row.put(RECEIVED_DATE, d);
        }
    }

    List<String> flags = new ArrayList<String>();
    for (Flags.Flag flag : mail.getFlags().getSystemFlags()) {
        if (flag == Flags.Flag.ANSWERED) {
            flags.add(FLAG_ANSWERED);
        } else if (flag == Flags.Flag.DELETED) {
            flags.add(FLAG_DELETED);
        } else if (flag == Flags.Flag.DRAFT) {
            flags.add(FLAG_DRAFT);
        } else if (flag == Flags.Flag.FLAGGED) {
            flags.add(FLAG_FLAGGED);
        } else if (flag == Flags.Flag.RECENT) {
            flags.add(FLAG_RECENT);
        } else if (flag == Flags.Flag.SEEN) {
            flags.add(FLAG_SEEN);
        }
    }
    flags.addAll(Arrays.asList(mail.getFlags().getUserFlags()));
    row.put(FLAGS, flags);

    String[] hdrs = mail.getHeader("X-Mailer");
    if (hdrs != null) {
        row.put(XMAILER, hdrs[0]);
    }
    return true;
}

From source file:mitm.application.djigzo.james.mailets.SMIMESign.java

@Override
public void serviceMail(Mail mail) {
    try {//  w  ww  .j  a v a  2  s.  co  m
        final InternetAddress originator = messageOriginatorIdentifier.getOriginator(mail);

        KeyAndCertificate signingKeyAndCertificate = actionExecutor
                .executeTransaction(new DatabaseAction<KeyAndCertificate>() {
                    @Override
                    public KeyAndCertificate doAction(Session session) throws DatabaseException {
                        Session previousSession = sessionManager.getSession();

                        sessionManager.setSession(session);

                        try {
                            return getSigningKeyAndCertificateAction(session, originator);
                        } finally {
                            sessionManager.setSession(previousSession);
                        }
                    }
                }, ACTION_RETRIES /* retry on a ConstraintViolationException */);

        MimeMessage message = mail.getMessage();

        if (signingKeyAndCertificate != null && message != null) {
            SMIMEBuilder sMIMEBuilder = new SMIMEBuilderImpl(message, protectedHeaders);

            sMIMEBuilder.setUseDeprecatedContentTypes(useDeprecatedContentTypes);

            X509Certificate signingCertificate = signingKeyAndCertificate.getCertificate();

            PrivateKey privateKey = signingKeyAndCertificate.getPrivateKey();

            if (privateKey != null && signingCertificate != null) {
                X509Certificate[] chain = getCertificateChain(signingCertificate);

                sMIMEBuilder.addCertificates(chain);

                SMIMESigningAlgorithm localAlgorithm = getSigningAlgorithm(mail);

                sMIMEBuilder.addSigner(privateKey, signingCertificate, localAlgorithm);

                getLogger().debug("Signing message. Signing algorithm: {}, Sign mode: {}", localAlgorithm,
                        signMode);

                sMIMEBuilder.sign(signMode);

                MimeMessage signed = sMIMEBuilder.buildMessage();

                if (signed != null) {
                    signed.saveChanges();

                    /*
                     * A new MimeMessage instance will be created. This makes ure that the 
                     * MimeMessage can be written by James (using writeTo()). The message-ID
                     * of the source message will be retained if told to do so
                     */
                    signed = retainMessageID ? new MimeMessageWithID(signed, message.getMessageID())
                            : new MimeMessage(signed);

                    mail.setMessage(signed);
                }
            } else {
                if (privateKey == null) {
                    getLogger().warn("PrivateKey is missing. Message cannot be signed.");
                }

                if (signingCertificate == null) {
                    getLogger().warn("signingCertificate is missing. Message cannot be signed.");
                }
            }
        } else {
            getLogger().debug("No signing certificate found, or message is null.");
        }
    } catch (MessagingException e) {
        getLogger().error("Error reading the message.", e);
    } catch (DatabaseException e) {
        getLogger().error("Error getting signing keyAndCertificate.", e);
    } catch (IOException e) {
        getLogger().error("Error signing the message.", e);
    } catch (SMIMEBuilderException e) {
        getLogger().error("Error signing the message.", e);
    }
}

From source file:mitm.application.djigzo.james.mailets.SMIMEHandler.java

@Override
public void serviceMail(final Mail mail) {
    try {/*www .ja v  a 2s. c om*/
        final MimeMessage sourceMessage = mail.getMessage();

        if (sourceMessage != null) {
            Messages messages = actionExecutor.executeTransaction(new DatabaseAction<Messages>() {
                @Override
                public Messages doAction(Session session) throws DatabaseException {
                    Session previousSession = sessionManager.getSession();

                    sessionManager.setSession(session);

                    try {
                        return handleMessageTransacted(mail);
                    } finally {
                        sessionManager.setSession(previousSession);
                    }
                }
            }, ACTION_RETRIES /* retry on a ConstraintViolationException */);

            if (messages != null) {
                try {
                    Collection<MimeSource> mimeSources = messages.getMimeSources();

                    /*
                     * Send all handled S/MIME message to the handledProcessor next processor 
                     */
                    for (MimeSource mimeSource : mimeSources) {
                        InputStream mimeInput = mimeSource.getMimeSource().getInputStream();

                        MimeMessage message = retainMessageID
                                ? new MimeMessageWithID(MailSession.getDefaultSession(), mimeInput,
                                        sourceMessage.getMessageID())
                                : new MimeMessage(MailSession.getDefaultSession(), mimeInput);

                        sendNewMessage(mail, mimeSource.getRecipients(), message, handledProcessor);
                    }

                    /*
                     * Send email to all the recipients that need the message unchanged
                     */
                    Set<MailAddress> asIsRecipients = messages.getAsIsRecipients();

                    if (CollectionUtils.isEmpty(asIsRecipients)) {
                        /*
                         * We no longer need the original Mail so ghost it
                         */
                        mail.setState(Mail.GHOST);
                    } else {
                        mail.setRecipients(asIsRecipients);
                    }
                } finally {
                    messages.close();
                }
            }
        }
    } catch (DatabaseException e) {
        getLogger().error("Error handling the message.", e);
    } catch (MessagingException e) {
        getLogger().error("Error handling the message.", e);
    } catch (IOException e) {
        getLogger().error("Error handling the message.", e);
    }
}

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

private MessageContext createMessageContextToMailWorker(MimeMessage msg) throws Exception {
    Object content = msg.getContent();
    if (!(content instanceof Multipart)) {
        return null;
    }// w ww.  j av a 2 s  .  c o  m
    MessageContext msgContext = null;
    TransportInDescription transportIn = configurationContext.getAxisConfiguration()
            .getTransportIn(org.apache.axis2.Constants.TRANSPORT_MAIL);
    TransportOutDescription transportOut = configurationContext.getAxisConfiguration()
            .getTransportOut(org.apache.axis2.Constants.TRANSPORT_MAIL);
    if ((transportIn != null) && (transportOut != null)) {
        // create Message Context
        msgContext = configurationContext.createMessageContext();
        msgContext.setTransportIn(transportIn);
        msgContext.setTransportOut(transportOut);
        msgContext.setServerSide(true);
        msgContext.setProperty(org.apache.axis2.transport.mail.Constants.CONTENT_TYPE, msg.getContentType());
        msgContext.setIncomingTransportName(org.apache.axis2.Constants.TRANSPORT_MAIL);

        MailBasedOutTransportInfo transportInfo = new MailBasedOutTransportInfo();
        Address[] mimefroms = msg.getFrom();
        if (mimefroms != null && mimefroms.length > 0) {
            EndpointReference fromEPR = new EndpointReference(
                    org.apache.axis2.transport.mail.Constants.MAILTO + ":" + msg.getFrom()[0].toString());
            transportInfo.setFrom(fromEPR);
        } else {
            String returnPath = getMailHeader(msg, org.apache.axis2.transport.mail.Constants.RETURN_PATH);
            returnPath = parseHeaderForLessThan(returnPath);
            if (returnPath != null) {
                EndpointReference fromEPR = new EndpointReference(
                        org.apache.axis2.transport.mail.Constants.MAILTO + ":" + returnPath);
                transportInfo.setFrom(fromEPR);
            }
        }

        // Save Message-Id to set as In-Reply-To on reply
        String smtpMessageId = msg.getMessageID();
        if (smtpMessageId != null) {
            transportInfo.setInReplyTo(smtpMessageId);
        }
        String inReplyTo = getMailHeader(msg, org.apache.axis2.transport.mail.Constants.IN_REPLY_TO);
        if (inReplyTo != null) {
            transportInfo.setInReplyTo(inReplyTo);
        }
        msgContext.setProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO, transportInfo);

        buildSOAPEnvelope(msg, msgContext);
        if (!fillMessageContextFromAvaiableData(msgContext, inReplyTo)) {
            return null;
        }
    }
    return msgContext;
}