Example usage for javax.mail.internet MimeMessage setContent

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

Introduction

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

Prototype

@Override
public void setContent(Multipart mp) throws MessagingException 

Source Link

Document

This method sets the Message's content to a Multipart object.

Usage

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

@Override
public void serviceMail(Mail mail) {
    try {//  w  w w.jav  a 2  s  . com
        MimeMessage sourceMessage = mail.getMessage();

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

        if (StringUtils.isNotEmpty(filename)) {
            newMessage.setFileName(filename);
        }

        Multipart mp = new MimeMultipart();

        HeaderMatcher contentMatcher = new ContentHeaderNameMatcher();

        mp.addBodyPart(BodyPartUtils.makeContentBodyPart(sourceMessage, contentMatcher));

        newMessage.setContent(mp);

        /* 
         * create a matcher that matches on everything expect content-* 
         */
        HeaderMatcher nonContentMatcher = new NotHeaderNameMatcher(contentMatcher);

        /* 
         * copy all non-content headers from source message to the new message 
         */
        HeaderUtils.copyHeaders(sourceMessage, newMessage, nonContentMatcher);

        newMessage.saveChanges();

        mail.setMessage(newMessage);
    } catch (MessagingException e) {
        getLogger().error("Error attaching the message.", e);
    } catch (IOException e) {
        getLogger().error("Error attaching the message.", e);
    }
}

From source file:net.sourceforge.vulcan.mailer.MessageAssembler.java

public MimeMessage constructMessage(String subscribers, ConfigDto config, ProjectStatusDto status, String html)
        throws MessagingException, AddressException {

    final MimeMessage message = new MimeMessage(mailSession);

    message.setSentDate(new Date());
    message.setFrom(new InternetAddress(config.getSenderAddress()));

    if (isNotBlank(config.getReplyToAddress())) {
        message.setReplyTo(InternetAddress.parse(config.getReplyToAddress()));
    }/*from   w  w w  .j av a 2 s  .c  om*/
    message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(subscribers));

    message.setSubject(status.getName() + ": " + status.getStatus());

    final Multipart multipart = new MimeMultipart();

    html = html.replaceAll("\\r", "");

    addMultipartBody(multipart, "text/html; charset=UTF-8", html);

    message.setContent(multipart);

    return message;
}

From source file:nz.co.testamation.common.mail.MimeMessageFactoryImpl.java

@Override
public Message create(Email email) {
    try {//  ww  w  . j a v a 2 s.c o  m
        EmailAddresses emailAddresses = email.getEmailAddresses();

        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setSubject(email.getSubject());
        mimeMessage.setFrom(new InternetAddress(emailAddresses.getFrom()));

        if (StringUtils.isNotBlank(emailAddresses.getReplyTo())) {
            mimeMessage.setReplyTo(InternetAddress.parse(emailAddresses.getReplyTo()));
        }

        addRecipients(mimeMessage, Message.RecipientType.TO, emailAddresses.getToAddresses());
        addRecipients(mimeMessage, Message.RecipientType.CC, emailAddresses.getCcAddresses());
        addRecipients(mimeMessage, Message.RecipientType.BCC, emailAddresses.getBccAddresses());

        mimeMessage.setContent(multipartMessageFactory.create(email));
        mimeMessage.setSentDate(new Date());

        return mimeMessage;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

From source file:nl.surfnet.coin.teams.control.JoinTeamController.java

private void sendJoinTeamMessage(final Team team, final Person person, final String message,
        final Locale locale) throws IllegalStateException, IOException {

    Object[] subjectValues = { team.getName() };
    final String subject = messageSource.getMessage(REQUEST_MEMBERSHIP_SUBJECT, subjectValues, locale);

    final Set<Member> admins = grouperTeamService.findAdmins(team);
    if (CollectionUtils.isEmpty(admins)) {
        throw new RuntimeException("Team '" + team.getName() + "' has no admins to mail invites");
    }/*from   w ww  .  jav a 2  s .c  om*/

    final String html = composeJoinRequestMailMessage(team, person, message, locale, "html");
    final String plainText = composeJoinRequestMailMessage(team, person, message, locale, "plaintext");

    final List<InternetAddress> bcc = new ArrayList<InternetAddress>();
    for (Member admin : admins) {
        try {
            bcc.add(new InternetAddress(admin.getEmail()));
        } catch (AddressException ae) {
            log.debug("Admin has malformed email address", ae);
        }
    }
    if (bcc.isEmpty()) {
        throw new RuntimeException(
                "Team '" + team.getName() + "' has no admins with valid email addresses to mail invites");
    }

    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws MessagingException {
            mimeMessage.addHeader("Precedence", "bulk");

            mimeMessage.setFrom(new InternetAddress(environment.getSystemEmail()));
            mimeMessage.setRecipients(Message.RecipientType.BCC, bcc.toArray(new InternetAddress[bcc.size()]));
            mimeMessage.setSubject(subject);

            MimeMultipart rootMixedMultipart = controllerUtil.getMimeMultipartMessageBody(plainText, html);
            mimeMessage.setContent(rootMixedMultipart);
        }
    };

    mailService.sendAsync(preparator);

}

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

@SuppressWarnings("deprecation")
@Override//from   w  w  w.j av a 2s  . c  o 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:org.apache.camel.component.mail.MailBinding.java

/**
 * Appends the Mail attachments from the Camel {@link MailMessage}
 *//*from   www . j  a  v a  2s.  c o m*/
protected void appendAttachmentsFromCamel(MimeMessage mimeMessage, MailConfiguration configuration,
        Exchange exchange) throws MessagingException, IOException {

    // Put parts in message
    mimeMessage.setContent(createMixedMultipartAttachments(configuration, exchange));
}

From source file:org.wf.dp.dniprorada.util.Mail.java

@Override
public void send() throws EmailException {

    try {// w ww .j  a va 2  s  . co  m
        log.info("init");
        MultiPartEmail oMultiPartEmail = new MultiPartEmail();
        oMultiPartEmail.setHostName(getHost());
        log.info("getHost()=" + getHost());
        oMultiPartEmail.addTo(getTo(), "receiver");
        log.info("getTo()=" + getTo());
        oMultiPartEmail.setFrom(getFrom(), getFrom());//"iGov"
        log.info("getFrom()=" + getFrom());
        oMultiPartEmail.setSubject(getHead());
        log.info("getHead()=" + getHead());

        oMultiPartEmail.setAuthentication(getAuthUser(), getAuthPassword());
        log.info("getAuthUser()=" + getAuthUser());
        log.info("getAuthPassword()=" + getAuthPassword());
        oMultiPartEmail.setSmtpPort(getPort());
        log.info("getPort()=" + getPort());
        oMultiPartEmail.setSSL(isSSL());
        log.info("isSSL()=" + isSSL());
        oMultiPartEmail.setTLS(isTLS());
        log.info("isTLS()=" + isTLS());

        oSession = oMultiPartEmail.getMailSession();
        MimeMessage oMimeMessage = new MimeMessage(oSession);

        //oMimeMessage.setFrom(new InternetAddress(getFrom(), "iGov", DEFAULT_ENCODING));
        oMimeMessage.setFrom(new InternetAddress(getFrom(), getFrom()));
        //oMimeMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(sTo, sToName, DEFAULT_ENCODING));
        oMimeMessage.addRecipient(Message.RecipientType.TO,
                new InternetAddress(getTo(), "recipient", DEFAULT_ENCODING));

        oMimeMessage.setSubject(getHead(), DEFAULT_ENCODING);

        _Attach(getBody());

        oMimeMessage.setContent(oMultiparts);

        //            oMimeMessage.getRecipients(Message.RecipientType.CC);
        Transport.send(oMimeMessage);
        log.info("[send]:Transport.send!");
    } catch (Exception exc) {
        log.error("[send]", exc);
        throw new EmailException("Error happened when sending email", exc);
    }
}

From source file:org.xwiki.mail.integration.JavaIntegrationTest.java

@Test
public void sendTextMail() throws Exception {
    // Step 1: Create a JavaMail Session
    Session session = Session.getInstance(this.configuration.getAllProperties());

    // Step 2: Create the Message to send
    MimeMessage message = new MimeMessage(session);
    message.setSubject("subject");
    message.setRecipient(RecipientType.TO, new InternetAddress("john@doe.com"));

    // Step 3: Add the Message Body
    Multipart multipart = new MimeMultipart("mixed");
    // Add text in the body
    multipart.addBodyPart(this.defaultBodyPartFactory.create("some text here",
            Collections.<String, Object>singletonMap("mimetype", "text/plain")));
    message.setContent(multipart);

    // We also test using some default BCC addresses from configuration in this test
    this.configuration.setBCCAddresses(Arrays.asList("bcc1@doe.com", "bcc2@doe.com"));

    // Ensure we do not reuse the same message identifier for multiple similar messages in this test
    MimeMessage message2 = new MimeMessage(message);
    message2.saveChanges();// w ww . j a  va2 s .  co  m
    MimeMessage message3 = new MimeMessage(message);
    message3.saveChanges();

    // Step 4: Send the mail and wait for it to be sent
    // Send 3 mails (3 times the same mail) to verify we can send several emails at once.
    MailListener memoryMailListener = this.componentManager.getInstance(MailListener.class, "memory");
    this.sender.sendAsynchronously(Arrays.asList(message, message2, message3), session, memoryMailListener);

    // Note: we don't test status reporting from the listener since this is already tested in the
    // ScriptingIntegrationTest test class.

    // Verify that the mails have been received (wait maximum 30 seconds).
    this.mail.waitForIncomingEmail(30000L, 3);
    MimeMessage[] messages = this.mail.getReceivedMessages();

    // Note: we're receiving 9 messages since we sent 3 with 3 recipients (2 BCC and 1 to)!
    assertEquals(9, messages.length);

    // Assert the email parts that are the same for all mails
    assertEquals("subject", messages[0].getHeader("Subject", null));
    assertEquals(1, ((MimeMultipart) messages[0].getContent()).getCount());
    BodyPart textBodyPart = ((MimeMultipart) messages[0].getContent()).getBodyPart(0);
    assertEquals("text/plain", textBodyPart.getHeader("Content-Type")[0]);
    assertEquals("some text here", textBodyPart.getContent());
    assertEquals("john@doe.com", messages[0].getHeader("To", null));

    // Note: We cannot assert that the BCC worked since by definition BCC information are not visible in received
    // messages ;) But we checked that we received 9 emails above so that's good enough.
}

From source file:com.threepillar.labs.meeting.email.EmailInviteImpl.java

@Override
public void sendInvite(final String subject, final String description, final Participant from,
        final List<Participant> attendees, final Date startDate, final Date endDate, final String location)
        throws Exception {

    this.properties.put("mail.smtp.socketFactory.port", properties.get("mail.smtp.port"));
    this.properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    this.properties.put("mail.smtp.socketFactory.fallback", "false");

    validate();//w ww.ja  va  2  s . c o  m

    LOG.info("Sending meeting invite");
    LOG.debug("Mail Properties :: " + this.properties);

    Session session;
    if (password != null) {
        session = Session.getInstance(this.properties, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
    } else {
        session = Session.getInstance(this.properties);
    }

    ICal cal = new ICal(subject, description, from, attendees, startDate, endDate, location);
    cal.init();

    StringBuffer sb = new StringBuffer();
    sb.append(from.getEmail());
    for (Participant bean : attendees) {
        if (sb.length() > 0) {
            sb.append(",");
        }
        sb.append(bean.getEmail());
    }
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from.getEmail()));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(sb.toString()));
    message.setSubject(subject);
    Multipart multipart = new MimeMultipart();
    MimeBodyPart iCal = new MimeBodyPart();
    iCal.setDataHandler(new DataHandler(new ByteArrayDataSource(new ByteArrayInputStream(cal.toByteArray()),
            "text/calendar;method=REQUEST;charset=\"UTF-8\"")));

    LOG.debug("Calender Request :: \n" + cal.toString());

    multipart.addBodyPart(iCal);
    message.setContent(multipart);
    Transport.send(message);
}

From source file:mitm.common.mail.filter.UnsupportedFormatStripper.java

private MimeMessage buildMessage(MimeMessage source, PartsContext context)
        throws MessagingException, IOException {
    List<Part> parts = context.getParts();

    assert (parts.size() > 0);

    MimeMessage newMessage;

    if (parts.size() > 1) {
        /* there is more than one S/MIME part so we need to create a multipart message */
        Multipart mp = new MimeMultipart();

        for (Part part : parts) {
            MimeBodyPart bodyPart = BodyPartUtils.toMimeBodyPart(part);

            mp.addBodyPart(bodyPart);// w  w  w  .ja v  a 2 s  .  c o m
        }

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

        newMessage.setContent(mp);
    } else {
        newMessage = BodyPartUtils.toMessage(parts.get(0), true /* clone */);
    }

    copyNonContentHeaders(source, newMessage);

    return newMessage;
}