Example usage for javax.mail.internet MimeMultipart MimeMultipart

List of usage examples for javax.mail.internet MimeMultipart MimeMultipart

Introduction

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

Prototype

public MimeMultipart(DataSource ds) throws MessagingException 

Source Link

Document

Constructs a MimeMultipart object and its bodyparts from the given DataSource.

Usage

From source file:com.xebialabs.xlt.ci.server.XLTestServerImplTest.java

private void verifyUploadRequest(final RecordedRequest request) throws IOException, MessagingException {
    assertEquals(request.getRequestLine(), "POST /api/internal/import/testspecid HTTP/1.1");
    assertEquals(request.getHeader("accept"), "application/json; charset=utf-8");
    assertEquals(request.getHeader("authorization"), "Basic YWRtaW46YWRtaW4=");
    assertThat(request.getHeader("Content-Length"), is(nullValue()));
    assertThat(request.getHeader("Transfer-Encoding"), is("chunked"));
    assertThat(request.getChunkSizes().get(0), greaterThan(0));
    assertThat(request.getChunkSizes().size(), greaterThan(0));

    assertTrue(request.getBodySize() > 0);

    ByteArrayDataSource bads = new ByteArrayDataSource(request.getBody().inputStream(), "multipart/mixed");
    MimeMultipart mp = new MimeMultipart(bads);
    assertTrue(request.getBodySize() > 0);

    assertEquals(mp.getCount(), 2);//  w w w  .j  a  v  a  2 s .c  om
    assertEquals(mp.getContentType(), "multipart/mixed");

    // TODO could do additional checks on metadata content
    BodyPart bodyPart1 = mp.getBodyPart(0);
    assertEquals(bodyPart1.getContentType(), "application/json; charset=utf-8");

    BodyPart bodyPart2 = mp.getBodyPart(1);
    assertEquals(bodyPart2.getContentType(), "application/zip");
}

From source file:org.tizzit.util.mail.Mail.java

public boolean sendPlaintextMail() {
    try {/*from  w ww .  ja v  a2  s .c  o m*/
        if (this.attachments.size() > 0) {
            MimeMultipart multiPart = new MimeMultipart("mixed");
            BodyPart plainTextBodyPart = new MimeBodyPart();
            plainTextBodyPart.setText(this.messageText);
            multiPart.addBodyPart(plainTextBodyPart);
            for (int i = 0; i < this.attachments.size(); i++) {
                multiPart.addBodyPart(this.attachments.get(i));
            }
            this.message.setContent(multiPart);
        } else {
            this.message.setText(this.messageText, this.encoding, "plain");
        }
        this.message.saveChanges();
        doSend();
    } catch (MessagingException exception) {
        log.error("Error sending plain text mail", exception);
        return false;
    }
    return true;
}

From source file:org.pentaho.reporting.platform.plugin.SimpleEmailComponent.java

private Multipart processAttachments(final Multipart multipartBody) throws MessagingException, IOException {

    if (getAttachmentContent() == null) {

        // We don't have a first attachment, won't even search for the others.
        return multipartBody;

    }/*w ww . j  a v  a  2  s . c om*/

    // We have attachments; Creating a multipart-mixed

    final MimeMultipart mixedMultipart = new MimeMultipart("mixed");

    // Add the first part
    final MimeBodyPart bodyPart = new MimeBodyPart();
    bodyPart.setContent(multipartBody);
    mixedMultipart.addBodyPart(bodyPart);

    // Process each of the attachments we have
    processSpecificAttachment(mixedMultipart, getAttachmentContent());
    processSpecificAttachment(mixedMultipart, getAttachmentContent2());
    processSpecificAttachment(mixedMultipart, getAttachmentContent3());

    return mixedMultipart;

}

From source file:lucee.runtime.net.smtp.SMTPClient.java

private MimeMessageAndSession createMimeMessage(lucee.runtime.config.Config config, String hostName, int port,
        String username, String password, long lifeTimesan, long idleTimespan, boolean tls, boolean ssl,
        boolean newConnection) throws MessagingException {

    SessionAndTransport sat = getSessionAndTransport(config, hostName, port, username, password, lifeTimesan,
            idleTimespan, timeout, tls, ssl, newConnection);
    /*Properties props = createProperties(config,hostName,port,username,password,tls,ssl,timeout);
    Authenticator auth=null;//ww  w . j a v  a2s.co m
     if(!StringUtil.isEmpty(username)) 
        auth=new SMTPAuthenticator( username, password );
             
               
       SessionAndTransport sat = newConnection?new SessionAndTransport(hash(props), props, auth,lifeTimesan,idleTimespan):
        SMTPConnectionPool.getSessionAndTransport(props,hash(props),auth,lifeTimesan,idleTimespan);
    */
    // Contacts
    SMTPMessage msg = new SMTPMessage(sat.session);
    if (from == null)
        throw new MessagingException("you have do define the from for the mail");
    //if(tos==null)throw new MessagingException("you have do define the to for the mail"); 

    checkAddress(from, charset);
    //checkAddress(tos,charset);

    msg.setFrom(from);
    //msg.setRecipients(Message.RecipientType.TO, tos);

    if (tos != null) {
        checkAddress(tos, charset);
        msg.setRecipients(Message.RecipientType.TO, tos);
    }
    if (ccs != null) {
        checkAddress(ccs, charset);
        msg.setRecipients(Message.RecipientType.CC, ccs);
    }
    if (bccs != null) {
        checkAddress(bccs, charset);
        msg.setRecipients(Message.RecipientType.BCC, bccs);
    }
    if (rts != null) {
        checkAddress(rts, charset);
        msg.setReplyTo(rts);
    }
    if (fts != null) {
        checkAddress(fts, charset);
        msg.setEnvelopeFrom(fts[0].toString());
    }

    // Subject and headers
    try {
        msg.setSubject(MailUtil.encode(subject, charset));
    } catch (UnsupportedEncodingException e) {
        throw new MessagingException("the encoding " + charset + " is not supported");
    }
    msg.setHeader("X-Mailer", xmailer);

    msg.setHeader("Date", getNow(timeZone));
    //msg.setSentDate(new Date());

    Multipart mp = null;

    // Only HTML
    if (plainText == null) {
        if (ArrayUtil.isEmpty(attachmentz) && ArrayUtil.isEmpty(parts)) {
            fillHTMLText(msg);
            setHeaders(msg, headers);
            return new MimeMessageAndSession(msg, sat);
        }
        mp = new MimeMultipart("related");
        mp.addBodyPart(getHTMLText());
    }
    // only Plain
    else if (htmlText == null) {
        if (ArrayUtil.isEmpty(attachmentz) && ArrayUtil.isEmpty(parts)) {
            fillPlainText(msg);
            setHeaders(msg, headers);
            return new MimeMessageAndSession(msg, sat);
        }
        mp = new MimeMultipart();
        mp.addBodyPart(getPlainText());
    }
    // Plain and HTML
    else {
        mp = new MimeMultipart("alternative");
        mp.addBodyPart(getPlainText());
        mp.addBodyPart(getHTMLText());

        if (!ArrayUtil.isEmpty(attachmentz) || !ArrayUtil.isEmpty(parts)) {
            MimeBodyPart content = new MimeBodyPart();
            content.setContent(mp);
            mp = new MimeMultipart();
            mp.addBodyPart(content);
        }
    }

    // parts
    if (!ArrayUtil.isEmpty(parts)) {
        Iterator<MailPart> it = parts.iterator();
        if (mp instanceof MimeMultipart)
            ((MimeMultipart) mp).setSubType("alternative");
        while (it.hasNext()) {
            mp.addBodyPart(toMimeBodyPart(it.next()));
        }
    }

    // Attachments
    if (!ArrayUtil.isEmpty(attachmentz)) {
        for (int i = 0; i < attachmentz.length; i++) {
            mp.addBodyPart(toMimeBodyPart(mp, config, attachmentz[i]));
        }
    }
    msg.setContent(mp);
    setHeaders(msg, headers);

    return new MimeMessageAndSession(msg, sat);
}

From source file:org.tizzit.util.mail.Mail.java

public boolean sendHtmlMail(String alternativePlaintextBody) {
    try {/* www. j  a  va  2s  . c o  m*/
        if (this.attachments.size() > 0) {
            MimeMultipart mainMultiPart = new MimeMultipart("mixed");
            if (alternativePlaintextBody != null) {
                MimeMultipart alternativeMultiPart = new MimeMultipart("alternative");
                MimeBodyPart plainTextBodyPart = new MimeBodyPart();
                MimeBodyPart htmlBodyPart = new MimeBodyPart();
                plainTextBodyPart.setText(alternativePlaintextBody, this.encoding, "plain");
                htmlBodyPart.setText(this.messageText, this.encoding, "html");
                alternativeMultiPart.addBodyPart(plainTextBodyPart);
                alternativeMultiPart.addBodyPart(htmlBodyPart);

                MimeBodyPart containerBodyPart = new MimeBodyPart();
                containerBodyPart.setContent(alternativeMultiPart);
                mainMultiPart.addBodyPart(containerBodyPart);
            } else { // without plain text alternative
                MimeBodyPart htmlBodyPart = new MimeBodyPart();
                htmlBodyPart.setText(this.messageText, this.encoding, "html");
                mainMultiPart.addBodyPart(htmlBodyPart);
            }
            for (int i = 0; i < this.attachments.size(); i++) {
                mainMultiPart.addBodyPart(this.attachments.get(i));
            }
            this.message.setContent(mainMultiPart);
        } else { // no attachments
            if (alternativePlaintextBody != null) {
                MimeMultipart mainMultipart = new MimeMultipart("alternative");
                MimeBodyPart plainTextBodyPart = new MimeBodyPart();
                MimeBodyPart htmlBodyPart = new MimeBodyPart();
                plainTextBodyPart.setText(alternativePlaintextBody, this.encoding, "plain");
                htmlBodyPart.setText(this.messageText, this.encoding, "html");
                mainMultipart.addBodyPart(plainTextBodyPart);
                mainMultipart.addBodyPart(htmlBodyPart);
                this.message.setContent(mainMultipart);
            } else { // no alternative plain text neither -> no MimeMessage!
                this.message.setContent(this.messageText, "text/html");
            }
        }
        this.message.saveChanges();
        doSend();
    } catch (MessagingException exception) {
        log.error("Error sending HTML mail", exception);
        return false;
    }
    return true;
}

From source file:gov.nist.healthcare.ttt.parsing.Parsing.java

public static SOAPWithAttachment parseMtom(String mtom) throws MessagingException, IOException {

    //        Parsing.fixMissingEndBoundry(mtom);
    MimeMultipart mp;//from  ww w. j  a v  a2 s.c om
    // String contentType = Parsing.findContentType(mtom);

    //     mp = new MimeMultipart(new ByteArrayDataSource(mtom.getBytes(), ""), new ContentType(contentType));
    mp = new MimeMultipart(new ByteArrayDataSource(mtom.getBytes(), "multipart/related"));
    SOAPWithAttachment swa = new SOAPWithAttachment();
    int count = mp.getCount();
    for (int i = 0; i < count; i++) {
        BodyPart bp = mp.getBodyPart(i);
        String contentType = bp.getContentType();
        if (contentType.startsWith("application/xop+xml")) {
            // SOAP
            ByteArrayInputStream content = (ByteArrayInputStream) bp.getContent();
            swa.setSoap(IOUtils.toString(content));

        } else {
            Object contentRaw = bp.getContent();
            if (contentRaw instanceof String) {
                String content = (String) bp.getContent();
                swa.getAttachment().add(content.getBytes());
            } else if (contentRaw instanceof SharedByteArrayInputStream) {
                SharedByteArrayInputStream content = (SharedByteArrayInputStream) bp.getContent();
                swa.getAttachment().add(read(content));
            } else {
                System.out.println("UNKNOWN ATTACHMENT TYPE = " + contentRaw.getClass().getName());
                swa.getAttachment().add(new String().getBytes());
            }
        }

        // System.out.println("contentype=" + bp.getContentType());
        //ByteArrayInputStream content = (ByteArrayInputStream) bp.getContent();
        //String contentString = IOUtils.toString(content);
        //String contentString = (String) bp.getContent();
        /*
        try {
        Envelope env = (Envelope) JAXB.unmarshal(new StringReader(contentString), Envelope.class);
        if (env.getHeader() == null && env.getBody() == null) {
            swa.getAttachment().add(Parsing.read(content));
            //swa.getAttachment().add(contentString.getBytes());
        } else {
            swa.setSoap(contentString);
        }
        } catch (Exception saxe) {
        // Not SOAP so must be attachment.
         swa.getAttachment().add(Parsing.read(content));
        //swa.getAttachment().add(contentString.getBytes());
        }
         */
    }

    if (swa.getAttachment() == null || swa.getAttachment().size() == 0) {
        byte[] document = Parsing.getDocumentFromSoap(swa.getSoap()).getBytes();
        Collection<byte[]> attachments = new ArrayList<byte[]>();
        attachments.add(document);
        swa.setAttachment(attachments);
    }

    return swa;
}

From source file:org.jahia.services.workflow.jbpm.custom.email.JBPMMailProducer.java

protected void fillContent(MailTemplate template, Message email, WorkItem workItem, JCRSessionWrapper session)
        throws Exception {
    String text = template.getText();
    String html = template.getHtml();
    List<AttachmentTemplate> attachmentTemplates = template.getAttachmentTemplates();

    if (html != null || !attachmentTemplates.isEmpty()) {
        // multipart
        MimeMultipart multipart = new MimeMultipart("related");

        BodyPart p = new MimeBodyPart();
        Multipart alternatives = new MimeMultipart("alternative");
        p.setContent(alternatives, "multipart/alternative");
        multipart.addBodyPart(p);/*from w  ww  .  java  2  s.  c  o m*/

        // html
        if (html != null) {
            BodyPart htmlPart = new MimeBodyPart();
            html = evaluateExpression(workItem, html, session);
            htmlPart.setContent(html, "text/html; charset=UTF-8");
            alternatives.addBodyPart(htmlPart);
        }

        // text
        if (text != null) {
            BodyPart textPart = new MimeBodyPart();
            text = evaluateExpression(workItem, text, session);
            textPart.setContent(text, "text/plain; charset=UTF-8");
            alternatives.addBodyPart(textPart);
        }

        // attachments
        if (!attachmentTemplates.isEmpty()) {
            addAttachments(template, workItem, multipart, session);
        }

        email.setContent(multipart);
    } else if (text != null) {
        // unipart
        text = evaluateExpression(workItem, text, session);
        email.setText(text);
    }
}

From source file:com.mirth.connect.connectors.http.HttpDispatcher.java

@Override
public Response send(ConnectorProperties connectorProperties, ConnectorMessage connectorMessage) {
    HttpDispatcherProperties httpDispatcherProperties = (HttpDispatcherProperties) connectorProperties;
    eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
            getDestinationName(), ConnectionStatusEventType.WRITING));

    String responseData = null;//from w w w . j  a v  a2  s.c om
    String responseError = null;
    String responseStatusMessage = null;
    Status responseStatus = Status.QUEUED;
    boolean validateResponse = false;

    CloseableHttpClient client = null;
    HttpRequestBase httpMethod = null;
    CloseableHttpResponse httpResponse = null;
    File tempFile = null;
    int socketTimeout = NumberUtils.toInt(httpDispatcherProperties.getSocketTimeout(), 30000);

    try {
        configuration.configureDispatcher(this, httpDispatcherProperties);

        long dispatcherId = getDispatcherId();
        client = clients.get(dispatcherId);
        if (client == null) {
            BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager(
                    socketFactoryRegistry.build());
            httpClientConnectionManager
                    .setSocketConfig(SocketConfig.custom().setSoTimeout(socketTimeout).build());
            HttpClientBuilder clientBuilder = HttpClients.custom()
                    .setConnectionManager(httpClientConnectionManager);
            HttpUtil.configureClientBuilder(clientBuilder);

            if (httpDispatcherProperties.isUseProxyServer()) {
                clientBuilder.setRoutePlanner(new DynamicProxyRoutePlanner());
            }

            client = clientBuilder.build();
            clients.put(dispatcherId, client);
        }

        URI hostURI = new URI(httpDispatcherProperties.getHost());
        String host = hostURI.getHost();
        String scheme = hostURI.getScheme();
        int port = hostURI.getPort();
        if (port == -1) {
            if (scheme.equalsIgnoreCase("https")) {
                port = 443;
            } else {
                port = 80;
            }
        }

        // Parse the content type field first, and then add the charset if needed
        ContentType contentType = ContentType.parse(httpDispatcherProperties.getContentType());
        Charset charset = null;
        if (contentType.getCharset() == null) {
            charset = Charset.forName(CharsetUtils.getEncoding(httpDispatcherProperties.getCharset()));
        } else {
            charset = contentType.getCharset();
        }

        if (httpDispatcherProperties.isMultipart()) {
            tempFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
        }

        HttpHost target = new HttpHost(host, port, scheme);

        httpMethod = buildHttpRequest(hostURI, httpDispatcherProperties, connectorMessage, tempFile,
                contentType, charset);

        HttpClientContext context = HttpClientContext.create();

        // authentication
        if (httpDispatcherProperties.isUseAuthentication()) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
            Credentials credentials = new UsernamePasswordCredentials(httpDispatcherProperties.getUsername(),
                    httpDispatcherProperties.getPassword());
            credsProvider.setCredentials(authScope, credentials);
            AuthCache authCache = new BasicAuthCache();
            RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder.<AuthSchemeProvider>create();

            if (AuthSchemes.DIGEST.equalsIgnoreCase(httpDispatcherProperties.getAuthenticationType())) {
                logger.debug("using Digest authentication");
                registryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory(charset));

                if (httpDispatcherProperties.isUsePreemptiveAuthentication()) {
                    processDigestChallenge(authCache, target, credentials, httpMethod, context);
                }
            } else {
                logger.debug("using Basic authentication");
                registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory(charset));

                if (httpDispatcherProperties.isUsePreemptiveAuthentication()) {
                    authCache.put(target, new BasicScheme());
                }
            }

            context.setCredentialsProvider(credsProvider);
            context.setAuthSchemeRegistry(registryBuilder.build());
            context.setAuthCache(authCache);

            logger.debug("using authentication with credentials: " + credentials);
        }

        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(socketTimeout)
                .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).build();
        context.setRequestConfig(requestConfig);

        // Set proxy information
        if (httpDispatcherProperties.isUseProxyServer()) {
            context.setAttribute(PROXY_CONTEXT_KEY, new HttpHost(httpDispatcherProperties.getProxyAddress(),
                    Integer.parseInt(httpDispatcherProperties.getProxyPort())));
        }

        // execute the method
        logger.debug(
                "executing method: type=" + httpMethod.getMethod() + ", uri=" + httpMethod.getURI().toString());
        httpResponse = client.execute(target, httpMethod, context);
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        logger.debug("received status code: " + statusCode);

        Map<String, List<String>> headers = new HashMap<String, List<String>>();
        for (Header header : httpResponse.getAllHeaders()) {
            List<String> list = headers.get(header.getName());

            if (list == null) {
                list = new ArrayList<String>();
                headers.put(header.getName(), list);
            }

            list.add(header.getValue());
        }

        connectorMessage.getConnectorMap().put("responseStatusLine", statusLine.toString());
        connectorMessage.getConnectorMap().put("responseHeaders",
                new MessageHeaders(new CaseInsensitiveMap(headers)));

        ContentType responseContentType = ContentType.get(httpResponse.getEntity());
        if (responseContentType == null) {
            responseContentType = ContentType.TEXT_PLAIN;
        }

        Charset responseCharset = charset;
        if (responseContentType.getCharset() != null) {
            responseCharset = responseContentType.getCharset();
        }

        final String responseBinaryMimeTypes = httpDispatcherProperties.getResponseBinaryMimeTypes();
        BinaryContentTypeResolver binaryContentTypeResolver = new BinaryContentTypeResolver() {
            @Override
            public boolean isBinaryContentType(ContentType contentType) {
                return HttpDispatcher.this.isBinaryContentType(responseBinaryMimeTypes, contentType);
            }
        };

        /*
         * First parse out the body of the HTTP response. Depending on the connector settings,
         * this could end up being a string encoded with the response charset, a byte array
         * representing the raw response payload, or a MimeMultipart object.
         */
        Object responseBody = "";

        // The entity could be null in certain cases such as 204 responses
        if (httpResponse.getEntity() != null) {
            // Only parse multipart if XML Body is selected and Parse Multipart is enabled
            if (httpDispatcherProperties.isResponseXmlBody()
                    && httpDispatcherProperties.isResponseParseMultipart()
                    && responseContentType.getMimeType().startsWith(FileUploadBase.MULTIPART)) {
                responseBody = new MimeMultipart(new ByteArrayDataSource(httpResponse.getEntity().getContent(),
                        responseContentType.toString()));
            } else if (binaryContentTypeResolver.isBinaryContentType(responseContentType)) {
                responseBody = IOUtils.toByteArray(httpResponse.getEntity().getContent());
            } else {
                responseBody = IOUtils.toString(httpResponse.getEntity().getContent(), responseCharset);
            }
        }

        /*
         * Now that we have the response body, we need to create the actual Response message
         * data. Depending on the connector settings this could be our custom serialized XML, a
         * Base64 string encoded from the raw response payload, or a string encoded from the
         * payload with the request charset.
         */
        if (httpDispatcherProperties.isResponseXmlBody()) {
            responseData = HttpMessageConverter.httpResponseToXml(statusLine.toString(), headers, responseBody,
                    responseContentType, httpDispatcherProperties.isResponseParseMultipart(),
                    httpDispatcherProperties.isResponseIncludeMetadata(), binaryContentTypeResolver);
        } else if (responseBody instanceof byte[]) {
            responseData = new String(Base64Util.encodeBase64((byte[]) responseBody), "US-ASCII");
        } else {
            responseData = (String) responseBody;
        }

        validateResponse = httpDispatcherProperties.getDestinationConnectorProperties().isValidateResponse();

        if (statusCode < HttpStatus.SC_BAD_REQUEST) {
            responseStatus = Status.SENT;
        } else {
            eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                    connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                    connectorProperties.getName(), "Received error response from HTTP server.", null));
            responseStatusMessage = ErrorMessageBuilder
                    .buildErrorResponse("Received error response from HTTP server.", null);
            responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(), responseData,
                    null);
        }
    } catch (Exception e) {
        eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                connectorProperties.getName(), "Error connecting to HTTP server.", e));
        responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("Error connecting to HTTP server", e);
        responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(),
                "Error connecting to HTTP server", e);
    } finally {
        try {
            HttpClientUtils.closeQuietly(httpResponse);

            // Delete temp files if we created them
            if (tempFile != null) {
                tempFile.delete();
                tempFile = null;
            }
        } finally {
            eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                    getDestinationName(), ConnectionStatusEventType.IDLE));
        }
    }

    return new Response(responseStatus, responseData, responseStatusMessage, responseError, validateResponse);
}

From source file:de.mendelson.comm.as2.message.AS2MessageCreation.java

/**Builds up a new message from the passed message parts
 * @param messageType one of the message types definfed in the class AS2Message
 *///from   ww  w .  j a  v a  2 s . c o  m
public AS2Message createMessage(Partner sender, Partner receiver, AS2Payload[] payloads, int messageType,
        String messageId) throws Exception {
    if (messageId == null) {
        messageId = UniqueId.createMessageId(sender.getAS2Identification(), receiver.getAS2Identification());
    }
    BCCryptoHelper cryptoHelper = new BCCryptoHelper();
    AS2MessageInfo info = new AS2MessageInfo();
    info.setMessageType(messageType);
    info.setSenderId(sender.getAS2Identification());
    info.setReceiverId(receiver.getAS2Identification());
    info.setSenderEMail(sender.getEmail());
    info.setMessageId(messageId);
    info.setDirection(AS2MessageInfo.DIRECTION_OUT);
    info.setSignType(receiver.getSignType());
    info.setEncryptionType(receiver.getEncryptionType());
    info.setRequestsSyncMDN(receiver.isSyncMDN());
    if (!receiver.isSyncMDN()) {
        info.setAsyncMDNURL(sender.getMdnURL());
    }
    info.setSubject(receiver.getSubject());
    try {
        info.setSenderHost(InetAddress.getLocalHost().getCanonicalHostName());
    } catch (UnknownHostException e) {
        //nop
    }
    //create message object to return
    AS2Message message = new AS2Message(info);
    //stores all the available body parts that have been prepared
    List<MimeBodyPart> contentPartList = new ArrayList<MimeBodyPart>();
    for (AS2Payload as2Payload : payloads) {
        //add payload
        message.addPayload(as2Payload);
        if (this.runtimeConnection != null) {
            MessageAccessDB messageAccess = new MessageAccessDB(this.configConnection, this.runtimeConnection);
            messageAccess.initializeOrUpdateMessage(info);
        }
        //no MIME message: single payload, unsigned, no CEM
        if (info.getSignType() == AS2Message.SIGNATURE_NONE && payloads.length == 1
                && info.getMessageType() != AS2Message.MESSAGETYPE_CEM) {
            return (this.createMessageNoMIME(message, receiver));
        }
        //MIME message
        MimeBodyPart bodyPart = new MimeBodyPart();
        String contentType = null;
        if (as2Payload.getContentType() == null) {
            contentType = receiver.getContentType();
        } else {
            contentType = as2Payload.getContentType();
        }
        bodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(as2Payload.getData(), contentType)));
        bodyPart.addHeader("Content-Type", contentType);
        if (as2Payload.getContentId() != null) {
            bodyPart.addHeader("Content-ID", as2Payload.getContentId());
        }
        if (receiver.getContentTransferEncoding() == AS2Message.CONTENT_TRANSFER_ENCODING_BASE64) {
            bodyPart.addHeader("Content-Transfer-Encoding", "base64");
        } else {
            bodyPart.addHeader("Content-Transfer-Encoding", "binary");
        }
        //prepare filename to not violate the MIME header rules
        if (as2Payload.getOriginalFilename() == null) {
            as2Payload.setOriginalFilename(new File(as2Payload.getPayloadFilename()).getName());
        }
        String newFilename = as2Payload.getOriginalFilename().replace(' ', '_');
        newFilename = newFilename.replace('@', '_');
        newFilename = newFilename.replace(':', '_');
        newFilename = newFilename.replace(';', '_');
        newFilename = newFilename.replace('(', '_');
        newFilename = newFilename.replace(')', '_');
        bodyPart.addHeader("Content-Disposition", "attachment; filename=" + newFilename);
        contentPartList.add(bodyPart);
    }
    Part contentPart = null;
    //sigle attachment? No CEM? Every CEM is in a multipart/related container
    if (contentPartList.size() == 1 && info.getMessageType() != AS2Message.MESSAGETYPE_CEM) {
        contentPart = contentPartList.get(0);
    } else {
        //build up a new MimeMultipart container for the multiple attachments, content-type
        //is "multipart/related"
        MimeMultipart multipart = null;
        //CEM messages are always in a multipart container (even the response which contains only a single
        //payload) with the subtype "application/ediint-cert-exchange+xml".
        if (info.getMessageType() == AS2Message.MESSAGETYPE_CEM) {
            multipart = new MimeMultipart("related; type=\"application/ediint-cert-exchange+xml\"");
        } else {
            multipart = new MimeMultipart("related");
        }
        for (MimeBodyPart bodyPart : contentPartList) {
            multipart.addBodyPart(bodyPart);
        }
        contentPart = new MimeMessage(Session.getInstance(System.getProperties(), null));
        contentPart.setContent(multipart, multipart.getContentType());
        ((MimeMessage) contentPart).saveChanges();
    }
    //should the content be compressed and enwrapped or just enwrapped?
    if (receiver.getCompressionType() == AS2Message.COMPRESSION_ZLIB) {
        info.setCompressionType(AS2Message.COMPRESSION_ZLIB);
        int uncompressedSize = contentPart.getSize();
        contentPart = this.compressPayload(receiver, contentPart);
        int compressedSize = contentPart.getSize();
        //sometimes size() is unable to determine the size of the compressed body part and will return -1. Dont log the
        //compression ratio in this case.
        if (uncompressedSize == -1 || compressedSize == -1) {
            if (this.logger != null) {
                this.logger.log(Level.INFO, this.rb.getResourceString("message.compressed.unknownratio",
                        new Object[] { info.getMessageId() }), info);
            }
        } else {
            if (this.logger != null) {
                this.logger.log(Level.INFO,
                        this.rb.getResourceString("message.compressed",
                                new Object[] { info.getMessageId(),
                                        AS2Tools.getDataSizeDisplay(uncompressedSize),
                                        AS2Tools.getDataSizeDisplay(compressedSize) }),
                        info);
            }
        }
    }
    //compute content mic. Try to use sign digest as hash alg. For unsigned messages take sha-1
    String digestOID = null;
    if (info.getSignType() == AS2Message.SIGNATURE_MD5) {
        digestOID = cryptoHelper.convertAlgorithmNameToOID(BCCryptoHelper.ALGORITHM_MD5);
    } else {
        digestOID = cryptoHelper.convertAlgorithmNameToOID(BCCryptoHelper.ALGORITHM_SHA1);
    }
    String mic = cryptoHelper.calculateMIC(contentPart, digestOID);
    if (info.getSignType() == AS2Message.SIGNATURE_MD5) {
        info.setReceivedContentMIC(mic + ", md5");
    } else {
        info.setReceivedContentMIC(mic + ", sha1");
    }
    this.enwrappInMessageAndSign(message, contentPart, sender, receiver);
    //encryption requested for the receiver?
    if (info.getEncryptionType() != AS2Message.ENCRYPTION_NONE) {
        String cryptAlias = this.encryptionCertManager
                .getAliasByFingerprint(receiver.getCryptFingerprintSHA1());
        this.encryptDataToMessage(message, cryptAlias, info.getEncryptionType(), receiver);
    } else {
        message.setRawData(message.getDecryptedRawData());
        if (this.logger != null) {
            this.logger.log(Level.INFO,
                    this.rb.getResourceString("message.notencrypted", new Object[] { info.getMessageId() }),
                    info);
        }
    }
    return (message);
}