Search code examples
apache-camelapache-camel-mailmimemultipart

How to send a Multipart Mail?


In our Project we need to send a Multipart Email with an empty text and then attached a xml. The layout is

... some headers...
Content-Type: multipart/mixed; boundary=XYZ 

--XYZ
Content-type: text/plain; charset=UTF-8 

--XYZ
Content-type: application/soap+xml; charset=UTF-8 
XML
--XYZ--

So we define a route like this

@Override
    public void configure() {
        from("direct:example")
                .process(exchange -> {
                    exchange.getIn().setHeader("from", "me");
                    exchange.getIn().setHeader("to", "you");
                    exchange.getIn().setHeader("subject", "subject");
                    MimeBodyPart textBodyPart = new MimeBodyPart();
                    textBodyPart.setText("", "UTF-8");
                    MimeBodyPart xmlBodyPart = new MimeBodyPart();
                    xmlBodyPart.setContent("<tag/>", "application/soap+xml; charset=UTF-8");
                    MimeMultipart multipart = new MimeMultipart(textBodyPart, xmlBodyPart);
                    exchange.getIn().setBody(multipart);
                    exchange.getIn().setHeader(Exchange.CONTENT_TYPE, multipart.getContentType());
                })
                .to("smtp://connectionString");
    }

triggering the route leads to Missing start boundary and debugging shows, that the multipart body is not correctly set/used by camel, because when parsing the mail, the body is empty. How to setup the multipart mail correctly when working with Apache Camel?


Solution

  • The body must be set as a string, so one hast to write the multipart to OutputStream then call .toString() on the stream.

    OutputStream outputStream = new FastByteArrayOutputStream();
    multipart.writeTo(outputStream);
    exchange.getIn().setBody(outputStream.toString());