Example usage for javax.mail.internet MimeMessage saveChanges

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

Introduction

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

Prototype

@Override
public void saveChanges() throws MessagingException 

Source Link

Document

Updates the appropriate header fields of this message to be consistent with the message's contents.

Usage

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

@Test
public void testSaveNewMessageRaw() throws IOException, MessagingException {
    File outputFile = File.createTempFile("mailUtilsTestRaw", ".eml");

    outputFile.deleteOnExit();/*from  w w w .ja v  a 2  s .  co m*/

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.addFrom(new InternetAddress[] { new InternetAddress("test@example.com") });
    message.addRecipients(RecipientType.TO, "recipient@example.com");
    message.setContent("test body", "text/plain");
    message.saveChanges();

    MailUtils.writeMessageRaw(message, new FileOutputStream(outputFile));

    MimeMessage loadedMessage = MailUtils.loadMessage(outputFile);

    String recipients = ArrayUtils.toString(loadedMessage.getRecipients(RecipientType.TO));

    assertEquals("{recipient@example.com}", recipients);

    String from = ArrayUtils.toString(loadedMessage.getFrom());

    assertEquals("{test@example.com}", from);
}

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

@Test
public void testCaseInsensitive() throws MessagingException, EncryptorException {
    HasValidPassword matcher = new HasValidPassword();

    MockMatcherConfig matcherConfig = new MockMatcherConfig("test", "matchOnError=false", mailetContext);

    matcher.init(matcherConfig);/*from   ww w.j  a va 2 s. c  o  m*/

    Mail mail = new MockMail();

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.setContent("test", "text/plain");
    message.setFrom(new InternetAddress("123456@example.com"));

    message.saveChanges();

    mail.setMessage(message);

    Collection<MailAddress> recipients = new LinkedList<MailAddress>();

    recipients.add(new MailAddress("TEST2@EXAMPLE.COM"));

    mail.setRecipients(recipients);

    Collection<?> result = matcher.match(mail);

    assertEquals(1, result.size());
    assertTrue(result.contains(new MailAddress("TEST2@EXAMPLE.COM")));

    DjigzoMailAttributes attributes = new DjigzoMailAttributesImpl(mail);

    Passwords passwords = attributes.getPasswords();

    assertNotNull(passwords);
    assertNotNull(passwords.get("test2@example.com"));
    assertEquals("test2", passwords.get("test2@example.com").getPassword());
    assertEquals("ID2", passwords.get("test2@example.com").getPasswordID());
}

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

@Test
public void testMatchDayValidityInterval() throws MessagingException, EncryptorException {
    HasValidPassword matcher = new HasValidPassword();

    MockMatcherConfig matcherConfig = new MockMatcherConfig("test", "matchOnError=false", mailetContext);

    matcher.init(matcherConfig);/*  ww w .  ja  va 2  s.c o  m*/

    Mail mail = new MockMail();

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.setContent("test", "text/plain");
    message.setFrom(new InternetAddress("123456@example.com"));

    message.saveChanges();

    mail.setMessage(message);

    Collection<MailAddress> recipients = new LinkedList<MailAddress>();

    recipients.add(new MailAddress("test2@example.com"));

    mail.setRecipients(recipients);

    Collection<?> result = matcher.match(mail);

    assertEquals(1, result.size());
    assertTrue(result.contains(new MailAddress("test2@example.com")));

    DjigzoMailAttributes attributes = new DjigzoMailAttributesImpl(mail);

    Passwords passwords = attributes.getPasswords();

    assertNotNull(passwords);
    assertNotNull(passwords.get("test2@example.com"));
    assertEquals("test2", passwords.get("test2@example.com").getPassword());
    assertEquals("ID2", passwords.get("test2@example.com").getPasswordID());
}

From source file:mitm.application.djigzo.ca.PFXMailBuilder.java

public MimeMessage createMessage() throws TemplateBuilderException {
    try {/*from  ww  w.j  a  v a  2  s. co m*/
        checkState();

        SimpleHash root = new SimpleHash();

        root.put("from", from);
        root.put("recipient", recipient);
        root.put("recipientLocal", EmailAddressUtils.getLocalPart(recipient));
        root.put("boundary", createBoundary());

        if (properties != null) {
            root.putAll(properties);
        }

        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        templateBuilder.buildTemplate(template, root, bos);

        MimeMessage templatedMessage = MailUtils.byteArrayToMessage(bos.toByteArray());

        templatedMessage.setFrom(from);

        if (recipient != null) {
            templatedMessage.setRecipient(RecipientType.TO, recipient);
        }

        replacePFX(templatedMessage);

        /*
         * Make sure the message has a message-ID
         */
        templatedMessage.saveChanges();

        return templatedMessage;
    } catch (MessagingException e) {
        throw new TemplateBuilderException(e);
    }
}

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

@Test
public void testMultipleMatches() throws MessagingException, EncryptorException {
    HasValidPassword matcher = new HasValidPassword();

    MockMatcherConfig matcherConfig = new MockMatcherConfig("test", "matchOnError=false", mailetContext);

    matcher.init(matcherConfig);/*from  w  ww.jav  a2 s  . c o m*/

    Mail mail = new MockMail();

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.setContent("test", "text/plain");
    message.setFrom(new InternetAddress("123456@example.com"));

    message.saveChanges();

    mail.setMessage(message);

    Collection<MailAddress> recipients = new LinkedList<MailAddress>();

    recipients.add(new MailAddress("test2@example.com"));
    recipients.add(new MailAddress("test5@example.com"));

    mail.setRecipients(recipients);

    Collection<?> result = matcher.match(mail);

    assertEquals(2, result.size());
    assertTrue(result.contains(new MailAddress("test2@example.com")));
    assertTrue(result.contains(new MailAddress("test5@example.com")));

    DjigzoMailAttributes attributes = new DjigzoMailAttributesImpl(mail);

    Passwords passwords = attributes.getPasswords();

    assertNotNull(passwords);
    assertNotNull(passwords.get("test2@example.com"));
    assertEquals("test2", passwords.get("test2@example.com").getPassword());
    assertEquals("ID2", passwords.get("test2@example.com").getPasswordID());
    assertNotNull(passwords.get("test5@example.com"));
    assertEquals("test5", passwords.get("test5@example.com").getPassword());
    assertEquals("ID5", passwords.get("test5@example.com").getPasswordID());
}

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

private MimeMessage createMessage(Mail mail, String subject, Address from, Address replyTo,
        Collection<Address> to, Collection<Address> cc, MailAddress sender, Collection<MailAddress> recipients,
        String body, Date date, SimpleHash root)
        throws MessagingException, MissingRecipientsException, TemplateException, IOException {
    setFreemarkerParam(root, SUBJECT_TEMPLATE_PARAM, subject);
    setFreemarkerParam(root, FROM_TEMPLATE_PARAM, from);
    setFreemarkerParam(root, REPLYTO_TEMPLATE_PARAM, replyTo);
    setFreemarkerParam(root, TO_TEMPLATE_PARAM, to);
    setFreemarkerParam(root, CC_TEMPLATE_PARAM, cc);
    setFreemarkerParam(root, SENDER_TEMPLATE_PARAM, sender);
    setFreemarkerParam(root, RECIPIENTS_TEMPLATE_PARAM, recipients);
    setFreemarkerParam(root, BODY_TEMPLATE_PARAM, body);
    setFreemarkerParam(root, DATE_TEMPLATE_PARAM, date);
    setFreemarkerParam(root, MAIL_TEMPLATE_PARAM, mail);
    setFreemarkerParam(root, BOUNDARY_TEMPLATE_PARAM, createBoundary());

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    Writer writer = new OutputStreamWriter(bos);

    getTemplate(mail, root).process(root, writer);

    MimeMessage templatedMessage = MailUtils.byteArrayToMessage(bos.toByteArray());

    /*//w w w.  j a va 2 s  .  c  o m
     * Make sure the message has a message-ID
     */
    templatedMessage.saveChanges();

    return templatedMessage;
}

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

@Override
public void serviceMail(Mail mail) {
    try {//from  w w w.j av a  2 s  . c o  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:com.eviware.soapui.impl.support.AbstractMockResponse.java

public String writeResponse(MockResult result, String responseContent) throws Exception {
    MimeMultipart mp = null;//  www. j a va 2  s. c  o m

    Operation operation = getMockOperation().getOperation();

    // variables needed for both multipart sections....
    boolean isXOP = isMtomEnabled() && isForceMtom();
    StringToStringMap contentIds = new StringToStringMap();

    // only support multipart for wsdl currently.....
    if (operation instanceof WsdlOperation) {
        if (operation == null) {
            throw new IllegalStateException("Missing WsdlOperation for mock response");
        }

        // preprocess only if neccessary
        if (isMtomEnabled() || isInlineFilesEnabled() || getAttachmentCount() > 0) {
            try {
                mp = new MimeMultipart();

                WsdlOperation wsdlOperation = ((WsdlOperation) operation);
                MessageXmlObject requestXmlObject = createMessageXmlObject(responseContent, wsdlOperation);
                MessageXmlPart[] requestParts = requestXmlObject.getMessageParts();
                for (MessageXmlPart requestPart : requestParts) {
                    if (prepareMessagePart(mp, contentIds, requestPart)) {
                        isXOP = true;
                    }
                }
                responseContent = requestXmlObject.getMessageContent();
            } catch (Exception e) {
                SoapUI.logError(e);
            }
        }

        responseContent = removeEmptyContent(responseContent);
    }

    if (isStripWhitespaces()) {
        responseContent = XmlUtils.stripWhitespaces(responseContent);
    }

    MockRequest request = result.getMockRequest();
    request.getHttpResponse().setStatus(this.getResponseHttpStatus());

    ByteArrayOutputStream outData = new ByteArrayOutputStream();

    // non-multipart request?
    String responseCompression = getResponseCompression();
    if (!isXOP && (mp == null || mp.getCount() == 0) && getAttachmentCount() == 0) {
        String encoding = getEncoding();
        if (responseContent == null) {
            responseContent = "";
        }

        byte[] content = encoding == null ? responseContent.getBytes() : responseContent.getBytes(encoding);

        if (!result.getResponseHeaders().containsKeyIgnoreCase("Content-Type")) {
            result.setContentType(getContentType());
        }

        String acceptEncoding = result.getMockRequest().getRequestHeaders().get("Accept-Encoding", "");
        if (AUTO_RESPONSE_COMPRESSION.equals(responseCompression) && acceptEncoding != null
                && acceptEncoding.toUpperCase().contains("GZIP")) {
            if (!headerExists("Content-Encoding", "gzip", result)) {
                result.addHeader("Content-Encoding", "gzip");
            }
            outData.write(CompressionSupport.compress(CompressionSupport.ALG_GZIP, content));
        } else if (AUTO_RESPONSE_COMPRESSION.equals(responseCompression) && acceptEncoding != null
                && acceptEncoding.toUpperCase().contains("DEFLATE")) {
            result.addHeader("Content-Encoding", "deflate");
            outData.write(CompressionSupport.compress(CompressionSupport.ALG_DEFLATE, content));
        } else {
            outData.write(content);
        }
    } else // won't get here if rest at the moment...
    {
        // make sure..
        if (mp == null) {
            mp = new MimeMultipart();
        }

        // init root part
        initRootPart(responseContent, mp, isXOP);

        // init mimeparts
        AttachmentUtils.addMimeParts(this, Arrays.asList(getAttachments()), mp, contentIds);

        // create request message
        MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION);
        message.setContent(mp);
        message.saveChanges();
        MimeMessageMockResponseEntity mimeMessageRequestEntity = new MimeMessageMockResponseEntity(message,
                isXOP, this);

        result.addHeader("Content-Type", mimeMessageRequestEntity.getContentType().getValue());
        result.addHeader("MIME-Version", "1.0");
        mimeMessageRequestEntity.writeTo(outData);
    }

    if (outData.size() > 0) {
        byte[] data = outData.toByteArray();

        if (responseCompression.equals(CompressionSupport.ALG_DEFLATE)
                || responseCompression.equals(CompressionSupport.ALG_GZIP)) {
            result.addHeader("Content-Encoding", responseCompression);
            data = CompressionSupport.compress(responseCompression, data);
        }
        if (result.getResponseHeaders().get("Transfer-Encoding") == null) {
            result.addHeader("Content-Length", "" + data.length);
        }
        result.writeRawResponseData(data);
    }

    return responseContent;
}

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

@Test
public void testRequestCertificatePendingAvailable() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig();

    String from = "from@example.com";
    String to = "to@example.com";

    proxy.addCertificateRequest(from);// w w w.j  a va  2s .c o m

    RequestSenderCertificate mailet = new RequestSenderCertificate();

    mailet.init(mailetConfig);

    MockMail mail = new MockMail();

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.setContent("test", "text/plain");
    message.setFrom(new InternetAddress(from));

    message.saveChanges();

    mail.setMessage(message);

    Collection<MailAddress> recipients = new LinkedList<MailAddress>();

    recipients.add(new MailAddress(to));

    mail.setRecipients(recipients);

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

    assertFalse(proxy.isUser(from));
    assertFalse(proxy.isUser(to));

    mailet.service(mail);

    assertEquals(INITIAL_KEY_STORE_SIZE, proxy.getKeyAndCertStoreSize());

    assertFalse(proxy.isUser(to));
    assertFalse(proxy.isUser(from));
}

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

@Test
public void testRequestCertificatePendingAvailableSkipIfAvailableFalse() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig();

    String from = "from@example.com";
    String to = "to@example.com";

    proxy.addCertificateRequest(from);/*w ww. j  av a 2s . c o m*/

    RequestSenderCertificate mailet = new RequestSenderCertificate();

    mailetConfig.setInitParameter("skipIfAvailable", "false");

    mailet.init(mailetConfig);

    MockMail mail = new MockMail();

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.setContent("test", "text/plain");
    message.setFrom(new InternetAddress(from));

    message.saveChanges();

    mail.setMessage(message);

    Collection<MailAddress> recipients = new LinkedList<MailAddress>();

    recipients.add(new MailAddress(to));

    mail.setRecipients(recipients);

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

    assertFalse(proxy.isUser(from));
    assertFalse(proxy.isUser(to));

    mailet.service(mail);

    assertEquals(INITIAL_KEY_STORE_SIZE + 1, proxy.getKeyAndCertStoreSize());

    assertFalse(proxy.isUser(to));
    assertTrue(proxy.isUser(from));
}