Example usage for javax.mail.internet MimeMessage getSubject

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

Introduction

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

Prototype

@Override
public String getSubject() throws MessagingException 

Source Link

Document

Returns the value of the "Subject" header field.

Usage

From source file:mitm.application.djigzo.james.matchers.SubjectPhoneNumber.java

@Override
public Collection<MailAddress> matchMail(Mail mail) throws MessagingException {
    List<MailAddress> matchingRecipients = null;

    String phoneNumber = null;/*from   ww w .  j  a  v a2s .  c  om*/

    MimeMessage message = mail.getMessage();

    /*
     * We need to check whether the original subject is stored in the mail attributes because
     * the check for the telephone number should be done on the original subject. The reason
     * for this is that the current subject can result in the detection of an incorrect
     * telephone number because the subject was changed because the subject trigger was
     * removed. 
     * 
     * Example:
     *  
     * original subject is: "test 123 [encrypt] 123456". The subject is: "test 123 123456" after
     * the trigger has been removed. The telephone nr 123123456 is detected instead of 123456.
     * 
     * See bug report: https://jira.djigzo.com/browse/GATEWAY-11
     * 
     */
    DjigzoMailAttributes mailAttributes = new DjigzoMailAttributesImpl(mail);

    String originalSubject = mailAttributes.getOriginalSubject();

    if (originalSubject == null) {
        originalSubject = message.getSubject();
    }

    if (StringUtils.isNotBlank(originalSubject)) {
        Matcher matcher = phoneNumberPattern.matcher(originalSubject);

        if (matcher.find()) {
            phoneNumber = matcher.group();

            /*
             * Remove the match and set the subject without the number. 
             * 
             * Note: the match should be removed from the current subject!!
             * 
             * Note2: using substringBeforeLast is only correct if the pattern matches the end
             * of the subject (which is the default). If the pattern matches something in the
             * middle, substringBeforeLast should not be used.
             */
            message.setSubject(StringUtils.substringBeforeLast(message.getSubject(), phoneNumber));
        }
    }

    if (StringUtils.isNotBlank(phoneNumber)) {
        matchingRecipients = MailAddressUtils.getRecipients(mail);

        int nrOfRecipients = CollectionUtils.getSize(matchingRecipients);

        if (nrOfRecipients == 1) {
            try {
                boolean added = addPhoneNumber(mail, matchingRecipients.get(0), phoneNumber);

                if (!added) {
                    /* 
                     * addPhoneNumbers has more thorough checks to see if the phone 
                     * number is valid and if not, there will be no matcj
                     */
                    matchingRecipients = Collections.emptyList();
                }
            } catch (DatabaseException e) {
                throw new MessagingException("Exception adding phone numbers.", e);
            }
        } else {
            /*
             * A telephone number was found but we cannot add the number to a users account
             * because we do not known to which recipient the number belongs. We will however
             * return all the recipients.
             */
            logger.warn("Found " + nrOfRecipients + " recipients but only one is supported.");
        }
    }

    if (matchingRecipients == null) {
        matchingRecipients = Collections.emptyList();
    }

    return matchingRecipients;
}

From source file:edu.hawaii.soest.hioos.storx.StorXDispatcher.java

/**
 * A method that executes the reading of data from the email account to the
 * RBNB server after all configuration of settings, connections to hosts,
 * and thread initiatizing occurs. This method contains the detailed code
 * for reading the data and interpreting the data files.
 *//*from  ww  w.  j av a  2 s . co m*/
protected boolean execute() {
    logger.debug("StorXDispatcher.execute() called.");
    boolean failed = true; // indicates overall success of execute()
    boolean messageProcessed = false; // indicates per message success

    // declare the account properties that will be pulled from the
    // email.account.properties.xml file
    String accountName = "";
    String server = "";
    String username = "";
    String password = "";
    String protocol = "";
    String dataMailbox = "";
    String processedMailbox = "";
    String prefetch = "";

    // fetch data from each sensor in the account list
    List accountList = this.xmlConfiguration.getList("account.accountName");

    for (Iterator aIterator = accountList.iterator(); aIterator.hasNext();) {

        int aIndex = accountList.indexOf(aIterator.next());

        // populate the email connection variables from the xml properties
        // file
        accountName = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").accountName");
        server = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").server");
        username = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").username");
        password = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").password");
        protocol = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").protocol");
        dataMailbox = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").dataMailbox");
        processedMailbox = (String) this.xmlConfiguration
                .getProperty("account(" + aIndex + ").processedMailbox");
        prefetch = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").prefetch");

        logger.debug("\n\nACCOUNT DETAILS: \n" + "accountName     : " + accountName + "\n"
                + "server          : " + server + "\n" + "username        : " + username + "\n"
                + "password        : " + password + "\n" + "protocol        : " + protocol + "\n"
                + "dataMailbox     : " + dataMailbox + "\n" + "processedMailbox: " + processedMailbox + "\n"
                + "prefetch        : " + prefetch + "\n");

        // get a connection to the mail server
        Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", protocol);
        props.setProperty("mail.imaps.partialfetch", prefetch);

        try {

            // create the imaps mail session
            this.mailSession = Session.getDefaultInstance(props, null);
            this.mailStore = mailSession.getStore(protocol);

        } catch (NoSuchProviderException nspe) {

            try {
                // pause for 10 seconds
                logger.debug(
                        "There was a problem connecting to the IMAP server. " + "Waiting 10 seconds to retry.");
                Thread.sleep(10000L);
                this.mailStore = mailSession.getStore(protocol);

            } catch (NoSuchProviderException nspe2) {

                logger.debug("There was an error connecting to the mail server. The " + "message was: "
                        + nspe2.getMessage());
                nspe2.printStackTrace();
                failed = true;
                return !failed;

            } catch (InterruptedException ie) {

                logger.debug("The thread was interrupted: " + ie.getMessage());
                failed = true;
                return !failed;

            }

        }

        try {

            this.mailStore.connect(server, username, password);

            // get folder references for the inbox and processed data box
            Folder inbox = mailStore.getFolder(dataMailbox);
            inbox.open(Folder.READ_WRITE);

            Folder processed = this.mailStore.getFolder(processedMailbox);
            processed.open(Folder.READ_WRITE);

            Message[] msgs;
            while (!inbox.isOpen()) {
                inbox.open(Folder.READ_WRITE);

            }
            msgs = inbox.getMessages();

            List<Message> messages = new ArrayList<Message>();
            Collections.addAll(messages, msgs);

            // sort the messages found in the inbox by date sent
            Collections.sort(messages, new Comparator<Message>() {

                public int compare(Message message1, Message message2) {
                    int value = 0;
                    try {
                        value = message1.getSentDate().compareTo(message2.getSentDate());
                    } catch (MessagingException e) {
                        e.printStackTrace();
                    }
                    return value;

                }

            });

            logger.debug("Number of messages: " + messages.size());
            for (Message message : messages) {

                // Copy the message to ensure we have the full attachment
                MimeMessage mimeMessage = (MimeMessage) message;
                MimeMessage copiedMessage = new MimeMessage(mimeMessage);

                // determine the sensor serial number for this message
                String messageSubject = copiedMessage.getSubject();
                Date sentDate = copiedMessage.getSentDate();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");

                // The subfolder of the processed mail folder (e.g. 2016-12);
                String destinationFolder = formatter.format(sentDate);
                logger.debug("Message date: " + sentDate + "\tNumber: " + copiedMessage.getMessageNumber());
                String[] subjectParts = messageSubject.split("\\s");
                String loggerSerialNumber = "SerialNumber";
                if (subjectParts.length > 1) {
                    loggerSerialNumber = subjectParts[2];

                }

                // Do we have a data attachment? If not, there's no data to
                // process
                if (copiedMessage.isMimeType("multipart/mixed")) {

                    logger.debug("Message size: " + copiedMessage.getSize());

                    MimeMessageParser parser = new MimeMessageParser(copiedMessage);
                    try {
                        parser.parse();

                    } catch (Exception e) {
                        logger.error("Failed to parse the MIME message: " + e.getMessage());
                        continue;
                    }
                    ByteBuffer messageAttachment = ByteBuffer.allocate(256); // init only

                    logger.debug("Has attachments: " + parser.hasAttachments());
                    for (DataSource dataSource : parser.getAttachmentList()) {
                        if (StringUtils.isNotBlank(dataSource.getName())) {
                            logger.debug(
                                    "Attachment: " + dataSource.getName() + ", " + dataSource.getContentType());

                            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                            IOUtils.copy(dataSource.getInputStream(), outputStream);
                            messageAttachment = ByteBuffer.wrap(outputStream.toByteArray());

                        }
                    }

                    // We now have the attachment and serial number. Parse the attachment 
                    // for the data components, look up the storXSource based on the serial 
                    // number, and push the data to the DataTurbine

                    // parse the binary attachment
                    StorXParser storXParser = new StorXParser(messageAttachment);

                    // iterate through the parsed framesMap and handle each
                    // frame
                    // based on its instrument type
                    BasicHierarchicalMap framesMap = (BasicHierarchicalMap) storXParser.getFramesMap();

                    Collection frameCollection = framesMap.getAll("/frames/frame");
                    Iterator framesIterator = frameCollection.iterator();

                    while (framesIterator.hasNext()) {

                        BasicHierarchicalMap frameMap = (BasicHierarchicalMap) framesIterator.next();

                        // logger.debug(frameMap.toXMLString(1000));

                        String frameType = (String) frameMap.get("type");
                        String sensorSerialNumber = (String) frameMap.get("serialNumber");

                        // handle each instrument type
                        if (frameType.equals("HDR")) {
                            logger.debug("This is a header frame. Skipping it.");

                        } else if (frameType.equals("STX")) {

                            try {

                                // handle StorXSource
                                StorXSource source = (StorXSource) sourceMap.get(sensorSerialNumber);
                                // process the data using the StorXSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else if (frameType.equals("SBE")) {

                            try {

                                // handle CTDSource
                                CTDSource source = (CTDSource) sourceMap.get(sensorSerialNumber);

                                // process the data using the CTDSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else if (frameType.equals("NLB")) {

                            try {

                                // handle ISUSSource
                                ISUSSource source = (ISUSSource) sourceMap.get(sensorSerialNumber);
                                // process the data using the ISUSSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else if (frameType.equals("NDB")) {

                            try {

                                // handle ISUSSource
                                ISUSSource source = (ISUSSource) sourceMap.get(sensorSerialNumber);
                                // process the data using the ISUSSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else {

                            logger.debug("The frame type " + frameType + " is not recognized. Skipping it.");
                        }

                    } // end while()

                    if (this.sourceMap.get(loggerSerialNumber) != null) {

                        // Note: Use message (not copiedMessage) when setting flags 

                        if (!messageProcessed) {
                            logger.info("Failed to process message: " + "Message Number: "
                                    + message.getMessageNumber() + "  " + "Logger Serial:"
                                    + loggerSerialNumber);
                            // leave it in the inbox, flagged as seen (read)
                            message.setFlag(Flags.Flag.SEEN, true);
                            logger.debug("Saw message " + message.getMessageNumber());

                        } else {

                            // message processed successfully. Create a by-month sub folder if it doesn't exist
                            // Copy the message and flag it deleted
                            Folder destination = processed.getFolder(destinationFolder);
                            boolean created = destination.create(Folder.HOLDS_MESSAGES);
                            inbox.copyMessages(new Message[] { message }, destination);
                            message.setFlag(Flags.Flag.DELETED, true);
                            logger.debug("Deleted message " + message.getMessageNumber());
                        } // end if()

                    } else {
                        logger.debug("There is no configuration information for " + "the logger serial number "
                                + loggerSerialNumber + ". Please add the configuration to the "
                                + "email.account.properties.xml configuration file.");

                    } // end if()

                } else {
                    logger.debug("This is not a data email since there is no "
                            + "attachment. Skipping it. Subject: " + messageSubject);

                } // end if()

            } // end for()

            // expunge messages and close the mail server store once we're
            // done
            inbox.expunge();
            this.mailStore.close();

        } catch (MessagingException me) {
            try {
                this.mailStore.close();

            } catch (MessagingException me2) {
                failed = true;
                return !failed;

            }
            logger.info(
                    "There was an error reading the mail message. The " + "message was: " + me.getMessage());
            me.printStackTrace();
            failed = true;
            return !failed;

        } catch (IOException me) {
            try {
                this.mailStore.close();

            } catch (MessagingException me3) {
                failed = true;
                return !failed;

            }
            logger.info("There was an I/O error reading the message part. The " + "message was: "
                    + me.getMessage());
            me.printStackTrace();
            failed = true;
            return !failed;

        } catch (IllegalStateException ese) {
            try {
                this.mailStore.close();

            } catch (MessagingException me4) {
                failed = true;
                return !failed;

            }
            logger.info("There was an error reading messages from the folder. The " + "message was: "
                    + ese.getMessage());
            failed = true;
            return !failed;

        } finally {

            try {
                this.mailStore.close();

            } catch (MessagingException me2) {
                logger.debug("Couldn't close the mail store: " + me2.getMessage());

            }

        }

    }

    return !failed;
}

From source file:mitm.common.pdf.MessagePDFBuilder.java

public void buildPDF(MimeMessage message, String replyURL, OutputStream pdfStream)
        throws DocumentException, MessagingException, IOException {
    Document document = createDocument();

    PdfWriter pdfWriter = createPdfWriter(document, pdfStream);

    document.open();//  w  w w .j  a  v a 2  s.  c o m

    String[] froms = null;

    try {
        froms = EmailAddressUtils.addressesToStrings(message.getFrom(), true /* mime decode */);
    } catch (MessagingException e) {
        logger.warn("From address is not a valid email address.");
    }

    if (froms != null) {
        for (String from : froms) {
            document.addAuthor(from);
        }
    }

    String subject = null;

    try {
        subject = message.getSubject();
    } catch (MessagingException e) {
        logger.error("Error getting subject.", e);
    }

    if (subject != null) {
        document.addSubject(subject);
        document.addTitle(subject);
    }

    String[] tos = null;

    try {
        tos = EmailAddressUtils.addressesToStrings(message.getRecipients(RecipientType.TO),
                true /* mime decode */);
    } catch (MessagingException e) {
        logger.warn("To is not a valid email address.");
    }

    String[] ccs = null;

    try {
        ccs = EmailAddressUtils.addressesToStrings(message.getRecipients(RecipientType.CC),
                true /* mime decode */);
    } catch (MessagingException e) {
        logger.warn("CC is not a valid email address.");
    }

    Date sentDate = null;

    try {
        sentDate = message.getSentDate();
    } catch (MessagingException e) {
        logger.error("Error getting sent date.", e);
    }

    Collection<Part> attachments = new LinkedList<Part>();

    String body = BodyPartUtils.getPlainBodyAndAttachments(message, attachments);

    attachments = preprocessAttachments(attachments);

    if (body == null) {
        body = MISSING_BODY;
    }

    /*
     * PDF does not have tab support so we convert tabs to spaces
     */
    body = StringReplaceUtils.replaceTabsWithSpaces(body, tabWidth);

    PdfPTable headerTable = new PdfPTable(2);

    headerTable.setHorizontalAlignment(Element.ALIGN_LEFT);
    headerTable.setWidthPercentage(100);
    headerTable.setWidths(new int[] { 1, 6 });
    headerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);

    Font headerFont = createHeaderFont();

    FontSelector headerFontSelector = createHeaderFontSelector();

    PdfPCell cell = new PdfPCell(new Paragraph("From:", headerFont));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

    headerTable.addCell(cell);

    String decodedFroms = StringUtils.defaultString(StringUtils.join(froms, ", "));

    headerTable.addCell(headerFontSelector.process(decodedFroms));

    cell = new PdfPCell(new Paragraph("To:", headerFont));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

    headerTable.addCell(cell);
    headerTable.addCell(headerFontSelector.process(StringUtils.defaultString(StringUtils.join(tos, ", "))));

    cell = new PdfPCell(new Paragraph("CC:", headerFont));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

    headerTable.addCell(cell);
    headerTable.addCell(headerFontSelector.process(StringUtils.defaultString(StringUtils.join(ccs, ", "))));

    cell = new PdfPCell(new Paragraph("Subject:", headerFont));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

    headerTable.addCell(cell);
    headerTable.addCell(headerFontSelector.process(StringUtils.defaultString(subject)));

    cell = new PdfPCell(new Paragraph("Date:", headerFont));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

    headerTable.addCell(cell);
    headerTable.addCell(ObjectUtils.toString(sentDate));

    cell = new PdfPCell(new Paragraph("Attachments:", headerFont));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

    headerTable.addCell(cell);
    headerTable
            .addCell(headerFontSelector.process(StringUtils.defaultString(getAttachmentHeader(attachments))));

    document.add(headerTable);

    if (replyURL != null) {
        addReplyLink(document, replyURL);
    }

    /*
     * Body table will contain the body of the message
     */
    PdfPTable bodyTable = new PdfPTable(1);
    bodyTable.setWidthPercentage(100f);

    bodyTable.setSplitLate(false);

    bodyTable.setSpacingBefore(15f);
    bodyTable.setHorizontalAlignment(Element.ALIGN_LEFT);

    addBodyAndAttachments(pdfWriter, document, bodyTable, body, attachments);

    Phrase footer = new Phrase(FOOTER_TEXT);

    PdfContentByte cb = pdfWriter.getDirectContent();

    ColumnText.showTextAligned(cb, Element.ALIGN_RIGHT, footer, document.right(), document.bottom(), 0);

    document.close();
}

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

/**
 * DOCUMENT ME!/*  w ww.  j ava  2  s .co m*/
 *
 * @param from DOCUMENT ME!
 * @param to DOCUMENT ME!
 * @param subjectPrefix DOCUMENT ME!
 * @param subjectSuffix DOCUMENT ME!
 * @param msgText DOCUMENT ME!
 * @param message DOCUMENT ME!
 * @param session DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws Exception DOCUMENT ME!
 * @throws IllegalArgumentException DOCUMENT ME!
 */
public static MimeMessage createNewMessage(Address from, Address[] to, String subjectPrefix,
        String subjectSuffix, String msgText, MimeMessage message, Session session) throws Exception {
    if (from == null) {
        throw new IllegalArgumentException("from addres cannot be null.");
    }

    if ((to == null) || (to.length <= 0)) {
        throw new IllegalArgumentException("to addres cannot be null.");
    }

    if (message == null) {
        throw new IllegalArgumentException("to message cannot be null.");
    }

    try {
        //Create the message
        MimeMessage newMessage = new MimeMessage(session);

        StringBuffer buffer = new StringBuffer();

        if (subjectPrefix != null) {
            buffer.append(subjectPrefix);
        }

        if (message.getSubject() != null) {
            buffer.append(message.getSubject());
        }

        if (subjectSuffix != null) {
            buffer.append(subjectSuffix);
        }

        if (buffer.length() > 0) {
            newMessage.setSubject(buffer.toString());
        }

        newMessage.setFrom(from);
        newMessage.addRecipients(Message.RecipientType.TO, to);

        //Create your new message part
        BodyPart messageBodyPart1 = new MimeBodyPart();
        messageBodyPart1.setText(msgText);

        //Create a multi-part to combine the parts
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart1);

        //Create and fill part for the forwarded content
        BodyPart messageBodyPart2 = new MimeBodyPart();
        messageBodyPart2.setDataHandler(message.getDataHandler());

        //Add part to multi part
        multipart.addBodyPart(messageBodyPart2);

        //Associate multi-part with message
        newMessage.setContent(multipart);

        newMessage.saveChanges();

        return newMessage;
    } finally {
    }
}

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

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

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

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

    MockMail mail = new MockMail();

    DjigzoMailAttributesImpl.getInstance(mail).setSecurityInfoTags(
            new SecurityInfoTags("[decrypted]", "[signed]", "[signed by: %s]", "[invalid]"));

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

    assertEquals("ik ook wipjam?", message.getSubject());

    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);

    assertEquals("ik ook wipjam? [invalid]", newMail.getMessage().getSubject());
}

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

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

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

    mailet.init(mailetConfig);//from  w  w  w  .  j  a va2  s .  c  om

    MockMail mail = new MockMail();

    DjigzoMailAttributesImpl.getInstance(mail).setSecurityInfoTags(
            new SecurityInfoTags("[decrypted]", "[signed]", "[signed by: %s]", "[invalid]"));

    MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/3-layer-encrypted.eml"));

    assertEquals("test simple message", message.getSubject());

    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);

    assertEquals("test simple message [decrypted] [decrypted] [decrypted]", newMail.getMessage().getSubject());
}

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

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

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

    mailet.init(mailetConfig);/*from   w w  w. j  a  va  2  s .  c  o m*/

    MockMail mail = new MockMail();

    DjigzoMailAttributesImpl.getInstance(mail).setSecurityInfoTags(
            new SecurityInfoTags("[decrypted]", "[signed]", "[signed by: %s]", "[invalid]"));

    MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/simple-text-body-clear-signed.eml"));

    assertEquals("test simple message", message.getSubject());

    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);

    assertEquals("test simple message [signed]", newMail.getMessage().getSubject());
}

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

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

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

    mailet.init(mailetConfig);/*from ww  w. ja  va 2s . c o m*/

    MockMail mail = new MockMail();

    DjigzoMailAttributesImpl.getInstance(mail).setSecurityInfoTags(
            new SecurityInfoTags("[decrypted]", "[signed]", "[signed by: %s]", "[invalid]"));

    MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/encrypted-no-decryption-key.eml"));

    assertEquals("RE: Test ", message.getSubject());

    mail.setMessage(message);

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

    recipients.add(new MailAddress("aap@noot.com"));

    mail.setRecipients(recipients);

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

    mailet.service(mail);

    /*
     * With non strict mode, the message is always handled if it's an S/MIME message because
     * the security info is added
     */
    assertEquals(1, sendMailEventListener.getMails().size());

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

    MimeMessage newMessage = newMail.getMessage();

    SMIMEInspector inspector = new SMIMEInspectorImpl(newMessage, null, "BC");

    /*
     * the message could not be decrypted
     */
    assertEquals(SMIMEType.ENCRYPTED, inspector.getSMIMEType());

    /*
     * Security information should be added
     */
    assertEquals("3DES, Key size: 168", newMessage.getHeader("X-Djigzo-Info-Encryption-Algorithm-0", ","));

    assertEquals("RE: Test ", newMail.getMessage().getSubject());
}

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

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

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

    mailet.init(mailetConfig);//  ww w .ja va2  s  .  c om

    MockMail mail = new MockMail();

    DjigzoMailAttributesImpl.getInstance(mail).setSecurityInfoTags(
            new SecurityInfoTags("[decrypted]", "[signed]", "[signed by: %s]", "[invalid]"));

    MimeMessage message = MailUtils
            .loadMessage(new File(testBase, "mail/clear-sign-missing-smime-ext-key-usage.eml"));

    assertEquals("test simple message", message.getSubject());

    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);

    assertEquals("test simple message [invalid]", newMail.getMessage().getSubject());
}

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

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

    try {//  ww  w.j ava 2  s.  c o  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);
    }
}