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:org.xwiki.mail.test.ui.MailTest.java

private void assertReceivedMessages(int expectedMatchingCount, String... expectedLines) throws Exception {
    StringBuilder builder = new StringBuilder();
    int count = 0;
    for (MimeMessage message : this.mail.getReceivedMessages()) {
        if (this.alreadyAssertedMessages.contains(message.getMessageID())) {
            continue;
        }/*from   www.  j a  v  a 2s. co m*/
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        message.writeTo(baos);
        String fullContent = baos.toString();
        boolean match = true;
        for (int i = 0; i < expectedLines.length; i++) {
            if (!fullContent.contains(expectedLines[i])) {
                match = false;
                break;
            }
        }
        if (!match) {
            builder.append("- Content [" + fullContent + "]").append('\n');
        } else {
            count++;
        }
        this.alreadyAssertedMessages.add(message.getMessageID());
    }
    StringBuilder expected = new StringBuilder();
    for (int i = 0; i < expectedLines.length; i++) {
        expected.append("- '" + expectedLines[i] + "'").append('\n');
    }
    assertEquals(
            String.format(
                    "We got [%s] mails matching the expected content instead of [%s]. We were expecting "
                            + "the following content:\n%s\nWe got the following:\n%s",
                    count, expectedMatchingCount, expected.toString(), builder.toString()),
            expectedMatchingCount, count);
}

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

@Test
public void testDKIMSignRelaxSimple8BitMessageIDIsDifferent() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig("test");

    Mailet mailet = new DKIMSign();

    mailetConfig.setInitParameter("privateKey", KEY_PAIR_PEM);
    mailetConfig.setInitParameter("signatureTemplate",
            "v=1; s=selector; c=relaxed/simple; d=example.com; " + "h=from:to; a=rsa-sha256; bh=; b=;");
    mailetConfig.setInitParameter("foldSignature", "true");

    mailet.init(mailetConfig);//www . j a v a 2s  .  co m

    MockMail mail = new MockMail();

    MimeMessage message = loadMessage("multipart_alternative_related.eml");

    assertEquals("<4AD824FC.108@djigzo.com>", message.getMessageID());

    mail.setMessage(message);

    mailet.service(mail);

    File resultFile = saveMessage(mail.getMessage(), "testDKIMSignRelaxSimple8BitMessageIDIsDifferent.eml");

    assertTrue(verify(resultFile));

    MimeMessage signed = MailUtils.loadMessage(resultFile);

    assertFalse("<4AD824FC.108@djigzo.com>".equals(signed.getMessageID()));
    assertTrue(signed.getMessageID().contains("JavaMail"));
}

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

@Test
public void testDKIMSignRelaxSimple() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig("test");

    Mailet mailet = new DKIMSign();

    mailetConfig.setInitParameter("privateKey", KEY_PAIR_PEM);
    mailetConfig.setInitParameter("signatureTemplate",
            "v=1; s=selector; c=relaxed/simple; d=example.com; " + "h=from:to; a=rsa-sha256; bh=; b=;");
    mailetConfig.setInitParameter("foldSignature", "true");

    mailet.init(mailetConfig);//from  ww w  .j a v a  2s.com

    MockMail mail = new MockMail();

    MimeMessage message = loadMessage("html-embedded-images.eml");

    assertEquals("<4AB65659.9060509@s2.mimesecure.com>", message.getMessageID());

    mail.setMessage(message);

    mailet.service(mail);

    File resultFile = saveMessage(mail.getMessage(), "testDKIMSignRelaxSimple.eml");

    assertTrue(verify(resultFile));

    MimeMessage signed = MailUtils.loadMessage(resultFile);

    assertEquals("<4AB65659.9060509@s2.mimesecure.com>", signed.getMessageID());
}

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

@Test
public void testConvertTo7BitNoConversion() throws IOException, MessagingException {
    MimeMessage message = loadMessage("multiple-attachments.eml");

    String messageID = message.getMessageID();

    assertFalse(MailUtils.convertTo7Bit(message));

    message.saveChanges();//from  w  w w  .j  a v a 2s .c o m

    MailUtils.validateMessage(message);

    // saveChanges changes the message ID so we cannot compare the result.
    // we need to set the original message id
    MimeMessageWithID mime = new MimeMessageWithID(message, messageID);

    mime.saveChanges();

    File file = new File("test/tmp/testConvertTo7BitNoConversion.eml");

    MailUtils.writeMessage(mime, file);

    // we need to correct CR/LF pairs because org only uses LF

    String result = FileUtils.readFileToString(file);

    result = StringUtils.replace(result, "\r\n", "\n").trim();

    String exp = FileUtils.readFileToString(new File(testBase, "multiple-attachments.eml"));

    exp = StringUtils.replace(exp, "\r\n", "\n").trim();

    assertEquals(exp, result);
}

From source file:se.inera.axel.shs.camel.ShsMessageDataFormatTest.java

@DirtiesContext
@Test//from w ww .  j  ava 2 s.c o m
public void testMarshal() throws Exception {
    Assert.assertNotNull(testShsMessage);

    resultEndpoint.expectedMessageCount(1);
    template.sendBody("direct:marshal", testShsMessage);

    resultEndpoint.assertIsSatisfied();
    List<Exchange> exchanges = resultEndpoint.getReceivedExchanges();
    Exchange exchange = exchanges.get(0);

    InputStream mimeStream = exchange.getIn().getBody(InputStream.class);

    MimeMessage mimeMessage = new MimeMessage(Session.getDefaultInstance(System.getProperties()), mimeStream);
    String[] mimeSubject = mimeMessage.getHeader("Subject");
    Assert.assertTrue("SHS Message".equalsIgnoreCase(mimeSubject[0]),
            "Subject is expected to be 'SHS Message' but was " + mimeSubject[0]);

    Assert.assertNull(mimeMessage.getMessageID());

    MimeMultipart multipart = (MimeMultipart) mimeMessage.getContent();
    Assert.assertEquals(multipart.getCount(), 2);

    BodyPart bodyPart = multipart.getBodyPart(1);
    String content = (String) bodyPart.getContent();
    Assert.assertEquals(content, ShsMessageTestObjectMother.DEFAULT_TEST_BODY);

    String contentType = bodyPart.getContentType();
    Assert.assertTrue(
            StringUtils.contains(contentType, ShsMessageTestObjectMother.DEFAULT_TEST_DATAPART_CONTENTTYPE),
            "Content type error");

    String encodings[] = bodyPart.getHeader("Content-Transfer-Encoding");
    Assert.assertNotNull(encodings);
    Assert.assertEquals(encodings.length, 1);
    Assert.assertEquals(encodings[0].toUpperCase(),
            ShsMessageTestObjectMother.DEFAULT_TEST_DATAPART_TRANSFERENCODING.toString().toUpperCase());

    mimeMessage.writeTo(System.out);
}

From source file:com.zimbra.cs.mime.Mime.java

/**
 * Returns the value of the <tt>Message-ID</tt> header, or <tt>null</tt>
 * if the header does not exist or has an empty value.
 *//*w w  w .  j a  va  2s  . c  o  m*/
public static String getMessageID(MimeMessage mm) {
    try {
        return Strings.emptyToNull(mm.getMessageID());
    } catch (MessagingException e) {
        return null;
    }
}

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

protected boolean accept(MimeMessage m) throws MessagingException {
    boolean accept = false;
    if (m.isSet(Flags.Flag.SEEN) || m.isSet(Flags.Flag.DELETED)) {
        return accept;
    }/*w  w w  .j a v  a2s  .c o  m*/
    int matches = 0;
    for (MessageFilter mf : filters) {
        if (mf.accept(m)) {
            matches++;
        }
    }
    if (matches == filters.size()) {
        log.trace("message [{}] matches filters", m.getMessageID());
        accept = true;
    } else {
        log.trace("Ignoring message [{}] filters not matched", m.getMessageID());
    }
    return accept;
}

From source file:com.studiostorti.ZimbraFlowHandler.java

@Override
public void handleRequest(ZimbraContext zimbraContext, SoapResponse soapResponse,
        ZimbraExceptionContainer zimbraExceptionContainer) {
    String requesterId = zimbraContext.getAuthenticatedAccontId();
    Mailbox mailbox = mMailboxManager.getMailboxByAccountId(requesterId);
    Account account = mProvisioning.getAccountById(requesterId);
    Map<String, String> args = new HashMap<String, String>();

    if (account == null) {
        soapResponse.setValue("reply", "KONon e' stato possibile trovare l'account : " + requesterId);

        return;//from  w w  w  . j a v a2  s  .co  m
    }

    OperationContext octxt = new OperationContext(account);
    String msgId = zimbraContext.getParameter("id", "");
    String namespace = zimbraContext.getParameter("namespace", "");
    String url = zimbraContext.getParameter("url", "");
    String user = account.getName();
    ZimbraLog.extensions
            .info("Azione ZimbraFlow richiesta da '" + user + "' per il messaggio: '" + msgId + "'");
    args.put("cUserEmail", user);

    Message item;
    if (!msgId.contains(":")) {
        try {
            item = mailbox.getMessageById(octxt, Integer.parseInt(msgId));
        } catch (Exception e) {
            soapResponse.setValue("reply",
                    "KONon e' stato possibile recuperare il messaggio (" + msgId + "): " + e.getMessage());

            return;
        }

        ZimbraLog.mailbox.info("ZimbraFlow mail id : " + msgId);
        args.put("cEmailUniqueID", account.getId() + ":" + msgId);
    } else {
        ZimbraLog.mailbox.info("ZimbraFlow il messaggio e' una cartella condivisa");
        String accountId = msgId.substring(0, msgId.indexOf(':'));
        String itemId = msgId.substring(msgId.indexOf(':') + 1);

        try {
            Mailbox ownerMailbox = mMailboxManager.getMailboxByAccountId(accountId);
            item = ownerMailbox.getMessageById(octxt, Integer.parseInt(itemId));
        } catch (Exception e) {
            soapResponse.setValue("reply",
                    "KONon e' stato possibile recuperare il messaggio (" + msgId + "): " + e.getMessage());

            return;
        }

        args.put("cEmailUniqueID", msgId);
    }
    if (item == null) {
        soapResponse.setValue("reply", "KONon e' stato possibile recuperare il messaggio (" + msgId + ".");

        return;
    }

    MimeMessage mimeMessage = null;
    try {
        mimeMessage = item.getMimeMessage();
        args.put("cEmailMessageID", mimeMessage.getMessageID());
    } catch (MessagingException e) {
        ZimbraLog.mailbox.warn("ZimbraFlow errore cEmailMessageID: " + e.getMessage());
    }

    byte[] mime = item.getContent();

    args.put("StreamBase64", Base64.encodeBase64String(mime));

    String subject;
    subject = item.getSubject();
    args.put("cSubject", subject);

    String body;
    try {
        body = getText(mimeMessage);
    } catch (MessagingException e) {
        ZimbraLog.mailbox.warn("ZimbraFlow errore cBody: " + e.getMessage());
        body = "";
    } catch (IOException e) {
        ZimbraLog.mailbox.warn("ZimbraFlow errore cBody: " + e.getMessage());
        body = "";
    }
    args.put("cBody", body);

    try {
        Address from = mimeMessage.getFrom()[0];
        args.put("cFrom", ((InternetAddress) from).getAddress());
    } catch (NullPointerException ne) {
        ZimbraLog.mailbox.warn("ZimbraFlow errore cFrom: " + ne.getMessage());
        args.put("cFrom", "");
    } catch (MessagingException e) {
        ZimbraLog.mailbox.warn("ZimbraFlow errore cFrom: " + e.getMessage());
        args.put("cFrom", "");
    }

    try {
        Address[] toRecipients = mimeMessage.getRecipients(javax.mail.Message.RecipientType.TO);
        String toString = "";
        for (Address to : toRecipients) {
            toString += ((InternetAddress) to).getAddress() + ",";
        }
        if (toString.length() > 0)
            args.put("cTO", toString.substring(0, toString.length() - 1));
        else
            args.put("cTO", toString);
    } catch (MessagingException ignored) {
    } catch (NullPointerException ne) {
        ZimbraLog.mailbox.warn("ZimbraFlow errore cTo: " + ne.getMessage());
        args.put("cTO", "");
    }

    try {
        Address[] ccRecipients = mimeMessage.getRecipients(javax.mail.Message.RecipientType.CC);
        String ccString = "";
        if (ccRecipients != null) {
            for (Address cc : ccRecipients) {
                ccString += ((InternetAddress) cc).getAddress() + ",";
            }
        }
        if (ccString.length() > 0)
            args.put("cCC", ccString.substring(0, ccString.length() - 1));
        else
            args.put("cCC", ccString);
    } catch (MessagingException ignored) {
    } catch (NullPointerException ne) {
        ZimbraLog.mailbox.warn("ZimbraFlow errore cCC: " + ne.getMessage());
        args.put("cCC", "");
    }

    try {
        Address[] bccRecipients = mimeMessage.getRecipients(javax.mail.Message.RecipientType.BCC);
        String bccString = "";
        if (bccRecipients != null) {
            for (Address bcc : bccRecipients) {
                bccString += ((InternetAddress) bcc).getAddress() + ",";
            }
        }
        if (bccString.length() > 0)
            args.put("cCCN", bccString.substring(0, bccString.length() - 1));
        else
            args.put("cCCN", bccString);

    } catch (MessagingException ignored) {
    } catch (NullPointerException ne) {
        ZimbraLog.mailbox.warn("ZimbraFlow errore cCCN: " + ne.getMessage());
        args.put("cCCN", "");
    }

    SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd hh:mm:ss");
    long date = item.getDate();
    args.put("cDateTime", dateFormat.format(new Date(date)));

    if (args.get("cDateTime") == null || args.get("cUserEmail") == null || args.get("StreamBase64") == null) {
        String message = "KONon sono stati trovati tutti i campi obbligatori:";
        if (args.get("cDateTime") == null)
            message += "\nManca il campo cDateTime";
        else if (args.get("cUserEmail") == null)
            message += "\nManca  il campo cUserEmail";
        else if (args.get("StreamBase64") == null)
            message += "\nManca il campo StreamBase64";

        soapResponse.setValue("reply", message);

        return;
    }

    SOAPClient soapClient = new SOAPClient(url, namespace);
    try {
        String res = soapClient.sendRequest(args);
        soapResponse.setValue("reply", res);
    } catch (SOAPException e) {
        ZimbraLog.mailbox.error("ZimbraFlow SOAP call exception: " + e.getMessage());
        soapResponse.setValue("reply", "KO" + e.getMessage());
    }
}

From source file:org.zilverline.core.IMAPCollection.java

private final boolean indexFolder(IndexWriter writer, Folder thisFolder) throws MessagingException {
    if (stopRequested) {
        log.info("Indexing stops, due to request");
        return false;
    }//from w  w  w .j  a va 2s .  co m
    if ((thisFolder.getType() & Folder.HOLDS_MESSAGES) != 0) {
        thisFolder.open(Folder.READ_ONLY);
        Message[] messages = thisFolder.getMessages(); // get refs to all msgs
        if (messages == null) {
            // dummy
            messages = new Message[0];
        }

        thisFolder.fetch(messages, PROFILE); // fetch headers

        log.debug("FOLDER: " + thisFolder.getFullName() + " messages=" + messages.length);

        for (int i = 0; i < messages.length; i++) {
            try {
                String msgID = null;
                if (messages[i] instanceof MimeMessage) {
                    MimeMessage mm = (MimeMessage) messages[i];
                    msgID = mm.getMessageID();
                }
                if (!md5DocumentCache.contains(msgID)) {
                    log.debug("new message added for message: " + msgID);
                    final Document doc = new Document();
                    doc.add(Field.Keyword(F_FOLDER, thisFolder.getFullName()));
                    doc.add(Field.Keyword("collection", name));
                    // index this message
                    indexMessage(doc, messages[i]);
                    // add it
                    writer.addDocument(doc);
                    md5DocumentCache.add(msgID);
                } else {
                    log.debug("existing message skipped for message: " + msgID);
                }
            } catch (Exception ioe) {
                // can be side effect of hosed up mail headers
                log.warn("Bad Message: " + messages[i], ioe);
                continue;
            }
        }

    }
    // recurse if possible
    if ((thisFolder.getType() & Folder.HOLDS_FOLDERS) != 0) {
        Folder[] far = thisFolder.list();
        if (far != null) {
            for (int i = 0; i < far.length; i++) {
                indexFolder(writer, far[i]);
            }
        }
    }
    if (thisFolder.isOpen()) {
        log.debug("Closing folder: " + thisFolder.getFullName());
        thisFolder.close(false); // false => do not expunge
    }

    return true;
}

From source file:org.silverpeas.components.mailinglist.service.job.MailProcessor.java

/**
 * Process an email, extracting attachments and constructing a Message.
 * @param mail the email to be processed.
 * @param mailingList the mailing list it is going to be affected to.
 * @param event the event which will be send at the end of all processing.
 * @throws MessagingException//from   w  w  w  .  j  a v a  2  s. c o  m
 * @throws IOException
 */
public void prepareMessage(MimeMessage mail, MessageListener mailingList, MessageEvent event)
        throws MessagingException, IOException {
    String sender = ((InternetAddress[]) mail.getFrom())[0].getAddress();
    if (!mailingList.checkSender(sender)) {
        return;
    }
    Message message = new Message();
    message.setComponentId(mailingList.getComponentId());
    message.setSender(sender);
    message.setSentDate(mail.getSentDate());
    message.setMessageId(mail.getMessageID());
    String[] referenceId = mail.getHeader(MAIL_HEADER_IN_REPLY_TO);
    if (referenceId == null || referenceId.length == 0) {
        referenceId = mail.getHeader(MAIL_HEADER_REFERENCES);
    }
    if (referenceId == null || referenceId.length == 0) {
        message.setReferenceId(null);
    } else {
        message.setReferenceId(referenceId[0]);
    }
    message.setTitle(mail.getSubject());
    Object content = mail.getContent();
    if (content instanceof Multipart) {
        processMultipart((Multipart) content, message);
    } else if (content instanceof String) {
        processBody((String) content, mail.getContentType(), message);
    }
    event.addMessage(message);
}