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.application.djigzo.james.mailets.RequestSenderCertificateTest.java

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

    RequestSenderCertificate mailet = new RequestSenderCertificate();

    // specify an unknown request handler so we can check the queue
    mailetConfig.setInitParameter("certificateRequestHandler", "unknown");

    mailet.init(mailetConfig);/*  www. j ava  2s .co  m*/

    MockMail mail = new MockMail();

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

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

    message.saveChanges();

    mail.setMessage(message);

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

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

    mail.setRecipients(recipients);

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

    mailet.service(mail);

    assertEquals(0, proxy.getCertificateRequestStoreSize());
    assertEquals(INITIAL_KEY_STORE_SIZE, proxy.getKeyAndCertStoreSize());
}

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

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

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

    KeyStore keyStore = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12");

    keyStore.load(new FileInputStream("test/resources/testdata/keys/testCertificates.p12"),
            "test".toCharArray());

    SystemServices.getKeyAndCertificateWorkflow().importKeyStore(keyStore, MissingKey.ADD_CERTIFICATE);

    assertEquals(22, proxy.getKeyAndCertStoreSize());

    RequestSenderCertificate mailet = new RequestSenderCertificate();

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

    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(22, proxy.getKeyAndCertStoreSize());

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

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

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

    RequestSenderCertificate mailet = new RequestSenderCertificate();

    mailet.init(mailetConfig);//  w w  w.ja v  a  2  s. c o m

    MockMail mail = new MockMail();

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

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

    message.saveChanges();

    mail.setMessage(message);

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

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

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

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

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

    RequestSenderCertificate mailet = new RequestSenderCertificate();

    mailet.init(mailetConfig);/*from  w w w .  j ava2s. co  m*/

    MockMail mail = new MockMail();

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

    String to = "to@example.com";

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

    message.saveChanges();

    mail.setMessage(message);

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

    recipients.add(new MailAddress(to));

    mail.setRecipients(recipients);

    mail.setSender(null);

    assertFalse(proxy.isUser(EmailAddressUtils.INVALID_EMAIL));
    assertFalse(proxy.isUser(to));

    mailet.service(mail);

    assertEquals(INITIAL_KEY_STORE_SIZE, proxy.getKeyAndCertStoreSize());

    assertFalse(proxy.isUser(to));
    assertFalse(proxy.isUser(EmailAddressUtils.INVALID_EMAIL));
}

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

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

    SendMailEventListenerImpl listener = new SendMailEventListenerImpl();

    mailetConfig.getMailetContext().setSendMailEventListener(listener);

    Mailet mailet = new BlackberrySMIMEAdapter();

    String template = FileUtils.readFileToString(new File("resources/templates/blackberry-smime-adapter.ftl"));

    autoTransactDelegator.setProperty("test@EXAMPLE.com", "pdfTemplate", template);

    mailetConfig.setInitParameter("log", "starting");
    /* use some dummy template because we must specify the default template */
    mailetConfig.setInitParameter("template", "sms.ftl");
    mailetConfig.setInitParameter("templateProperty", "pdfTemplate");

    mailet.init(mailetConfig);//w w w .j a  va 2 s . co m

    MockMail mail = new MockMail();

    mail.setState(Mail.DEFAULT);

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

    MimeBodyPart emptyPart = new MimeBodyPart();

    message.setContent(emptyPart, "text/plain");

    message.saveChanges();

    mail.setMessage(message);

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

    recipients.add(new MailAddress("123@EXAMPLE.com"));

    mail.setRecipients(recipients);

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

    mailet.service(mail);

    assertEquals(message, mail.getMessage());

    try {
        MailUtils.validateMessage(message);

        fail();
    } catch (IOException e) {
        // expected. The message should be corrupt
    }
}

From source file:com.eviware.soapui.impl.wsdl.submit.filters.HttpRequestFilter.java

@SuppressWarnings("deprecation")
@Override/*  w w  w. j a  v  a  2 s. co m*/
public void filterHttpRequest(SubmitContext context, HttpRequestInterface<?> request) {
    HttpRequestBase httpMethod = (HttpRequestBase) context.getProperty(BaseHttpRequestTransport.HTTP_METHOD);

    String path = PropertyExpander.expandProperties(context, request.getPath());
    StringBuffer query = new StringBuffer();
    String encoding = System.getProperty("soapui.request.encoding", StringUtils.unquote(request.getEncoding()));

    StringToStringMap responseProperties = (StringToStringMap) context
            .getProperty(BaseHttpRequestTransport.RESPONSE_PROPERTIES);

    MimeMultipart formMp = "multipart/form-data".equals(request.getMediaType())
            && httpMethod instanceof HttpEntityEnclosingRequestBase ? new MimeMultipart() : null;

    RestParamsPropertyHolder params = request.getParams();

    for (int c = 0; c < params.getPropertyCount(); c++) {
        RestParamProperty param = params.getPropertyAt(c);

        String value = PropertyExpander.expandProperties(context, param.getValue());
        responseProperties.put(param.getName(), value);

        List<String> valueParts = sendEmptyParameters(request)
                || (!StringUtils.hasContent(value) && param.getRequired())
                        ? RestUtils.splitMultipleParametersEmptyIncluded(value,
                                request.getMultiValueDelimiter())
                        : RestUtils.splitMultipleParameters(value, request.getMultiValueDelimiter());

        // skip HEADER and TEMPLATE parameter encoding (TEMPLATE is encoded by
        // the URI handling further down)
        if (value != null && param.getStyle() != ParameterStyle.HEADER
                && param.getStyle() != ParameterStyle.TEMPLATE && !param.isDisableUrlEncoding()) {
            try {
                if (StringUtils.hasContent(encoding)) {
                    value = URLEncoder.encode(value, encoding);
                    for (int i = 0; i < valueParts.size(); i++)
                        valueParts.set(i, URLEncoder.encode(valueParts.get(i), encoding));
                } else {
                    value = URLEncoder.encode(value);
                    for (int i = 0; i < valueParts.size(); i++)
                        valueParts.set(i, URLEncoder.encode(valueParts.get(i)));
                }
            } catch (UnsupportedEncodingException e1) {
                SoapUI.logError(e1);
                value = URLEncoder.encode(value);
                for (int i = 0; i < valueParts.size(); i++)
                    valueParts.set(i, URLEncoder.encode(valueParts.get(i)));
            }
            // URLEncoder replaces space with "+", but we want "%20".
            value = value.replaceAll("\\+", "%20");
            for (int i = 0; i < valueParts.size(); i++)
                valueParts.set(i, valueParts.get(i).replaceAll("\\+", "%20"));
        }

        if (param.getStyle() == ParameterStyle.QUERY && !sendEmptyParameters(request)) {
            if (!StringUtils.hasContent(value) && !param.getRequired())
                continue;
        }

        switch (param.getStyle()) {
        case HEADER:
            for (String valuePart : valueParts)
                httpMethod.addHeader(param.getName(), valuePart);
            break;
        case QUERY:
            if (formMp == null || !request.isPostQueryString()) {
                for (String valuePart : valueParts) {
                    if (query.length() > 0)
                        query.append('&');

                    query.append(URLEncoder.encode(param.getName()));
                    query.append('=');
                    if (StringUtils.hasContent(valuePart))
                        query.append(valuePart);
                }
            } else {
                try {
                    addFormMultipart(request, formMp, param.getName(), responseProperties.get(param.getName()));
                } catch (MessagingException e) {
                    SoapUI.logError(e);
                }
            }

            break;
        case TEMPLATE:
            try {
                value = getEncodedValue(value, encoding, param.isDisableUrlEncoding(),
                        request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
                path = path.replaceAll("\\{" + param.getName() + "\\}", value == null ? "" : value);
            } catch (UnsupportedEncodingException e) {
                SoapUI.logError(e);
            }
            break;
        case MATRIX:
            try {
                value = getEncodedValue(value, encoding, param.isDisableUrlEncoding(),
                        request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
            } catch (UnsupportedEncodingException e) {
                SoapUI.logError(e);
            }

            if (param.getType().equals(XmlBoolean.type.getName())) {
                if (value.toUpperCase().equals("TRUE") || value.equals("1")) {
                    path += ";" + param.getName();
                }
            } else {
                path += ";" + param.getName();
                if (StringUtils.hasContent(value)) {
                    path += "=" + value;
                }
            }
        case PLAIN:
            break;
        }
    }

    if (request.getSettings().getBoolean(HttpSettings.FORWARD_SLASHES))
        path = PathUtils.fixForwardSlashesInPath(path);

    if (PathUtils.isHttpPath(path)) {
        try {
            // URI(String) automatically URLencodes the input, so we need to
            // decode it first...
            URI uri = new URI(path, request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
            context.setProperty(BaseHttpRequestTransport.REQUEST_URI, uri);
            java.net.URI oldUri = httpMethod.getURI();
            httpMethod.setURI(new java.net.URI(oldUri.getScheme(), oldUri.getUserInfo(), oldUri.getHost(),
                    oldUri.getPort(), (uri.getPath()) == null ? "/" : uri.getPath(), oldUri.getQuery(),
                    oldUri.getFragment()));
        } catch (Exception e) {
            SoapUI.logError(e);
        }
    } else if (StringUtils.hasContent(path)) {
        try {
            java.net.URI oldUri = httpMethod.getURI();
            String pathToSet = StringUtils.hasContent(oldUri.getRawPath()) && !"/".equals(oldUri.getRawPath())
                    ? oldUri.getRawPath() + path
                    : path;
            java.net.URI newUri = URIUtils.createURI(oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(),
                    pathToSet, oldUri.getQuery(), oldUri.getFragment());
            httpMethod.setURI(newUri);
            context.setProperty(BaseHttpRequestTransport.REQUEST_URI,
                    new URI(newUri.toString(), request.getSettings().getBoolean(HttpSettings.ENCODED_URLS)));
        } catch (Exception e) {
            SoapUI.logError(e);
        }
    }

    if (query.length() > 0 && !request.isPostQueryString()) {
        try {
            java.net.URI oldUri = httpMethod.getURI();
            httpMethod.setURI(URIUtils.createURI(oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(),
                    oldUri.getRawPath(), query.toString(), oldUri.getFragment()));
        } catch (Exception e) {
            SoapUI.logError(e);
        }
    }

    if (request instanceof RestRequest) {
        String acceptEncoding = ((RestRequest) request).getAccept();
        if (StringUtils.hasContent(acceptEncoding)) {
            httpMethod.setHeader("Accept", acceptEncoding);
        }
    }

    if (formMp != null) {
        // create request message
        try {
            if (request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest) {
                String requestContent = PropertyExpander.expandProperties(context, request.getRequestContent(),
                        request.isEntitizeProperties());
                if (StringUtils.hasContent(requestContent)) {
                    initRootPart(request, requestContent, formMp);
                }
            }

            for (Attachment attachment : request.getAttachments()) {
                MimeBodyPart part = new PreencodedMimeBodyPart("binary");

                if (attachment instanceof FileAttachment<?>) {
                    String name = attachment.getName();
                    if (StringUtils.hasContent(attachment.getContentID())
                            && !name.equals(attachment.getContentID()))
                        name = attachment.getContentID();

                    part.setDisposition(
                            "form-data; name=\"" + name + "\"; filename=\"" + attachment.getName() + "\"");
                } else
                    part.setDisposition("form-data; name=\"" + attachment.getName() + "\"");

                part.setDataHandler(new DataHandler(new AttachmentDataSource(attachment)));

                formMp.addBodyPart(part);
            }

            MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION);
            message.setContent(formMp);
            message.saveChanges();
            RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity(
                    message, request);
            ((HttpEntityEnclosingRequest) httpMethod).setEntity(mimeMessageRequestEntity);
            httpMethod.setHeader("Content-Type", mimeMessageRequestEntity.getContentType().getValue());
            httpMethod.setHeader("MIME-Version", "1.0");
        } catch (Throwable e) {
            SoapUI.logError(e);
        }
    } else if (request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest) {
        if (StringUtils.hasContent(request.getMediaType()))
            httpMethod.setHeader("Content-Type", getContentTypeHeader(request.getMediaType(), encoding));

        if (request.isPostQueryString()) {
            try {
                ((HttpEntityEnclosingRequest) httpMethod).setEntity(new StringEntity(query.toString()));
            } catch (UnsupportedEncodingException e) {
                SoapUI.logError(e);
            }
        } else {
            String requestContent = PropertyExpander.expandProperties(context, request.getRequestContent(),
                    request.isEntitizeProperties());
            List<Attachment> attachments = new ArrayList<Attachment>();

            for (Attachment attachment : request.getAttachments()) {
                if (attachment.getContentType().equals(request.getMediaType())) {
                    attachments.add(attachment);
                }
            }

            if (StringUtils.hasContent(requestContent) && attachments.isEmpty()) {
                try {
                    byte[] content = encoding == null ? requestContent.getBytes()
                            : requestContent.getBytes(encoding);
                    ((HttpEntityEnclosingRequest) httpMethod).setEntity(new ByteArrayEntity(content));
                } catch (UnsupportedEncodingException e) {
                    ((HttpEntityEnclosingRequest) httpMethod)
                            .setEntity(new ByteArrayEntity(requestContent.getBytes()));
                }
            } else if (attachments.size() > 0) {
                try {
                    MimeMultipart mp = null;

                    if (StringUtils.hasContent(requestContent)) {
                        mp = new MimeMultipart();
                        initRootPart(request, requestContent, mp);
                    } else if (attachments.size() == 1) {
                        ((HttpEntityEnclosingRequest) httpMethod)
                                .setEntity(new InputStreamEntity(attachments.get(0).getInputStream(), -1));

                        httpMethod.setHeader("Content-Type",
                                getContentTypeHeader(request.getMediaType(), encoding));
                    }

                    if (((HttpEntityEnclosingRequest) httpMethod).getEntity() == null) {
                        if (mp == null)
                            mp = new MimeMultipart();

                        // init mimeparts
                        AttachmentUtils.addMimeParts(request, attachments, mp, new StringToStringMap());

                        // create request message
                        MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION);
                        message.setContent(mp);
                        message.saveChanges();
                        RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity(
                                message, request);
                        ((HttpEntityEnclosingRequest) httpMethod).setEntity(mimeMessageRequestEntity);
                        httpMethod.setHeader("Content-Type", getContentTypeHeader(
                                mimeMessageRequestEntity.getContentType().getValue(), encoding));
                        httpMethod.setHeader("MIME-Version", "1.0");
                    }
                } catch (Exception e) {
                    SoapUI.logError(e);
                }
            }
        }
    }
}

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

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

    RequestSenderCertificate mailet = new RequestSenderCertificate();

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

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

    MockMail mail = new MockMail();

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

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

    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));
    assertFalse(proxy.isUser(from));
}

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

private void createMessageFromTemplate(Mail mail)
        throws MessagingException, MissingRecipientsException, TemplateException, IOException, PartException {
    SimpleHash root = new SimpleHash();

    /*//from  w w  w  . j a v  a2s.c  o m
     * Create a message from a template
     */
    MimeMessage containerMessage = createMessage(mail, root);

    /*
     * Copy all non content headers from source to destination
     */
    HeaderMatcher nonContentMatcher = new NotHeaderNameMatcher(new ContentHeaderNameMatcher());

    HeaderUtils.copyHeaders(mail.getMessage(), containerMessage, nonContentMatcher);

    /*
     * We now need to replace the s/mime attachment from the template with the real attachment
     */
    replaceSMIMEAttachment(containerMessage, mail.getMessage());

    containerMessage.saveChanges();

    /*
     * A new MimeMessage instance will be created. This makes ure that the 
     * MimeMessage can be written by James (using writeTo()).
     */
    mail.setMessage(new MimeMessage(containerMessage));
}

From source file:mitm.common.mail.repository.hibernate.MailRepositoryImplTest.java

@Test
public void testPerformance() throws Exception {
    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    int messageSize = 50 * SizeUtils.MB;

    byte[] content = new byte[messageSize];

    Arrays.fill(content, (byte) 'A');

    message.setContent(content, "application/octet-stream");
    message.saveChanges();
    MailUtils.validateMessage(message);/*www  .  j  a  va  2s  .  co m*/

    long start = System.currentTimeMillis();

    int nrOfItems = 10;

    for (int i = 0; i < nrOfItems; i++) {
        proxy.addItem(DEFAULT_REPOSITORY, message,
                InternetAddress.parse("test" + i + "@example.com, other@example.com", false),
                new InternetAddress("sender" + i + "@example.com", false), "127.0.0." + i, null, null);
    }

    double msec = (double) (System.currentTimeMillis() - start) / nrOfItems;

    System.out.println("msec / add:" + msec);

    assertTrue("Can fail on slower systems", msec < 10000);

    start = System.currentTimeMillis();

    List<? extends MailRepositoryItem> items = proxy.getItems(DEFAULT_REPOSITORY, 0, Integer.MAX_VALUE);

    for (MailRepositoryItem item : items) {
        System.out.println(item.getID());
    }

    msec = (double) (System.currentTimeMillis() - start) / nrOfItems;

    System.out.println("msec / get:" + msec);

    assertTrue("Can fail on slower systems", msec < 100);
}

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

@Override
public void setMessageRead(MimeMessage msg) throws MailException {
    try {// ww  w  .  j  ava  2  s .  co  m
        if (msg.isSet(Flags.Flag.SEEN) || msg.isSet(Flags.Flag.DELETED)) {
            return;
        }
        msg.setFlag(Flags.Flag.SEEN, true);
        msg.setFlag(Flags.Flag.DELETED, deleteFlag);
        try {
            // When accessing a POP3 mailbox the sun provider
            // doesn't allow you to save changes to the message
            // status (curious)
            // To delete the messages, you should do setPurge(true);
            // This will work with imap mailboxes

            // Note that this does nothing for ComsNetClient
            msg.saveChanges();
        } catch (Exception e) {
            ;
        }
    } catch (Exception e) {
        throw new MailException(e);
    }
}