Search in sources :

Example 36 with BodyPart

use of javax.mail.BodyPart in project camel by apache.

the class MimeMultipartDataFormat method marshal.

@Override
public void marshal(Exchange exchange, Object graph, OutputStream stream) throws NoTypeConversionAvailableException, MessagingException, IOException {
    if (multipartWithoutAttachment || headersInline || exchange.getIn().hasAttachments()) {
        ContentType contentType = getContentType(exchange);
        // remove the Content-Type header. This will be wrong afterwards...
        exchange.getOut().removeHeader(Exchange.CONTENT_TYPE);
        byte[] bodyContent = ExchangeHelper.convertToMandatoryType(exchange, byte[].class, graph);
        Session session = Session.getInstance(System.getProperties());
        MimeMessage mm = new MimeMessage(session);
        MimeMultipart mp = new MimeMultipart(multipartSubType);
        BodyPart part = new MimeBodyPart();
        writeBodyPart(bodyContent, part, contentType);
        mp.addBodyPart(part);
        for (Map.Entry<String, Attachment> entry : exchange.getIn().getAttachmentObjects().entrySet()) {
            String attachmentFilename = entry.getKey();
            Attachment attachment = entry.getValue();
            part = new MimeBodyPart();
            part.setDataHandler(attachment.getDataHandler());
            part.setFileName(MimeUtility.encodeText(attachmentFilename, "UTF-8", null));
            String ct = attachment.getDataHandler().getContentType();
            contentType = new ContentType(ct);
            part.setHeader(CONTENT_TYPE, ct);
            if (!contentType.match("text/*") && binaryContent) {
                part.setHeader(CONTENT_TRANSFER_ENCODING, "binary");
            }
            // Set headers to the attachment
            for (String headerName : attachment.getHeaderNames()) {
                List<String> values = attachment.getHeaderAsList(headerName);
                for (String value : values) {
                    part.setHeader(headerName, value);
                }
            }
            mp.addBodyPart(part);
            exchange.getOut().removeAttachment(attachmentFilename);
        }
        mm.setContent(mp);
        // a String
        if (headersInline && includeHeaders != null) {
            for (Map.Entry<String, Object> entry : exchange.getIn().getHeaders().entrySet()) {
                if (includeHeaders.matcher(entry.getKey()).matches()) {
                    String headerStr = ExchangeHelper.convertToType(exchange, String.class, entry.getValue());
                    if (headerStr != null) {
                        mm.setHeader(entry.getKey(), headerStr);
                    }
                }
            }
        }
        mm.saveChanges();
        Enumeration<?> hl = mm.getAllHeaders();
        List<String> headers = new ArrayList<String>();
        if (!headersInline) {
            while (hl.hasMoreElements()) {
                Object ho = hl.nextElement();
                if (ho instanceof Header) {
                    Header h = (Header) ho;
                    exchange.getOut().setHeader(h.getName(), h.getValue());
                    headers.add(h.getName());
                }
            }
            mm.saveChanges();
        }
        mm.writeTo(stream, headers.toArray(new String[0]));
    } else {
        // keep the original data
        InputStream is = ExchangeHelper.convertToMandatoryType(exchange, InputStream.class, graph);
        IOHelper.copyAndCloseInput(is, stream);
    }
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) ContentType(javax.mail.internet.ContentType) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) Attachment(org.apache.camel.Attachment) DefaultAttachment(org.apache.camel.impl.DefaultAttachment) Header(javax.mail.Header) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart) Map(java.util.Map) Session(javax.mail.Session)

Example 37 with BodyPart

use of javax.mail.BodyPart in project camel by apache.

the class MailConverters method toString.

/**
     * Converts the given JavaMail multipart to a String body, where the content-type of the multipart
     * must be text based (ie start with text). Can return null.
     */
@Converter
public static String toString(Multipart multipart) throws MessagingException, IOException {
    int size = multipart.getCount();
    for (int i = 0; i < size; i++) {
        BodyPart part = multipart.getBodyPart(i);
        Object content = part.getContent();
        while (content instanceof MimeMultipart) {
            if (multipart.getCount() < 1) {
                break;
            }
            part = ((MimeMultipart) content).getBodyPart(0);
            content = part.getContent();
        }
        if (part.getContentType().toLowerCase().startsWith("text")) {
            return part.getContent().toString();
        }
    }
    return null;
}
Also used : BodyPart(javax.mail.BodyPart) MimeMultipart(javax.mail.internet.MimeMultipart) FallbackConverter(org.apache.camel.FallbackConverter) Converter(org.apache.camel.Converter) TypeConverter(org.apache.camel.TypeConverter) IOConverter(org.apache.camel.converter.IOConverter)

Example 38 with BodyPart

use of javax.mail.BodyPart in project camel by apache.

the class MailConverters method toString.

/**
     * Converts the given JavaMail message to a String body.
     * Can return null.
     */
@Converter
public static String toString(Message message) throws MessagingException, IOException {
    Object content = message.getContent();
    while (content instanceof MimeMultipart) {
        MimeMultipart multipart = (MimeMultipart) content;
        if (multipart.getCount() > 0) {
            BodyPart part = multipart.getBodyPart(0);
            content = part.getContent();
        }
    }
    if (content != null) {
        return content.toString();
    }
    return null;
}
Also used : BodyPart(javax.mail.BodyPart) MimeMultipart(javax.mail.internet.MimeMultipart) FallbackConverter(org.apache.camel.FallbackConverter) Converter(org.apache.camel.Converter) TypeConverter(org.apache.camel.TypeConverter) IOConverter(org.apache.camel.converter.IOConverter)

Example 39 with BodyPart

use of javax.mail.BodyPart in project opennms by OpenNMS.

the class JavaMailer method buildMessage.

/**
 * Build a complete message ready for sending.
 *
 * @return completed message, ready to be passed to Transport.sendMessage
 * @throws org.opennms.javamail.JavaMailerException if any of the underlying operations fail
 */
public Message buildMessage() throws JavaMailerException {
    try {
        checkEnvelopeAndContents();
        MimeMessage message = initializeMessage();
        // The next line has been commented, because it prevents the usage of internationalized characters and makes the email unreadable.
        // String encodedText = MimeUtility.encodeText(getMessageText(), m_charSet, m_encoding);
        String encodedText = getMessageText();
        if ((getFileName() == null) && (getInputStream() == null)) {
            message.setContent(encodedText, m_contentType + "; charset=" + m_charSet);
        } else if (getFileName() == null) {
            BodyPart streamBodyPart = new MimeBodyPart();
            streamBodyPart.setDataHandler(new DataHandler(new InputStreamDataSource(m_inputStreamName, m_inputStreamContentType, m_inputStream)));
            streamBodyPart.setFileName(m_inputStreamName);
            streamBodyPart.setHeader("Content-Transfer-Encoding", "base64");
            streamBodyPart.setDisposition(Part.ATTACHMENT);
            MimeMultipart mp = new MimeMultipart();
            mp.addBodyPart(streamBodyPart);
            message.setContent(mp);
        } else {
            BodyPart bp = new MimeBodyPart();
            bp.setContent(encodedText, m_contentType + "; charset=" + m_charSet);
            MimeMultipart mp = new MimeMultipart();
            mp.addBodyPart(bp);
            mp.addBodyPart(createFileAttachment(new File(getFileName())));
            message.setContent(mp);
        }
        message.setHeader("X-Mailer", getMailer());
        message.setSentDate(new Date());
        message.saveChanges();
        return message;
    } catch (AddressException e) {
        LOG.error("Java Mailer Addressing exception: ", e);
        throw new JavaMailerException("Java Mailer Addressing exception: ", e);
    } catch (MessagingException e) {
        LOG.error("Java Mailer messaging exception: ", e);
        throw new JavaMailerException("Java Mailer messaging exception: ", e);
    // } catch (UnsupportedEncodingException e) {
    // log().error("Java Mailer messaging exception: ", e);
    // throw new JavaMailerException("Java Mailer encoding exception: ", e);
    }
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) MessagingException(javax.mail.MessagingException) AddressException(javax.mail.internet.AddressException) DataHandler(javax.activation.DataHandler) MimeBodyPart(javax.mail.internet.MimeBodyPart) File(java.io.File) Date(java.util.Date)

Example 40 with BodyPart

use of javax.mail.BodyPart in project rest.li by linkedin.

the class TestMIMEReaderDrain method testSinglePartialTopRemaining.

@Test(dataProvider = "allTypesOfBodiesDataSource")
public void testSinglePartialTopRemaining(final int chunkSize, final List<MimeBodyPart> bodyPartList) throws Exception {
    //Execute the request, verify the correct header came back to ensure the server took the proper drain actions
    //and return the payload so we can assert deeper.
    executeRequestWithDrainStrategy(chunkSize, bodyPartList, SINGLE_PARTIAL_TOP_REMAINING, "onDrainComplete");
    //Single part drains the first 6 then the top level drains all of remaining
    List<SinglePartMIMEDrainReaderCallbackImpl> singlePartMIMEReaderCallbacks = _currentMultiPartMIMEReaderCallback.getSinglePartMIMEReaderCallbacks();
    Assert.assertEquals(singlePartMIMEReaderCallbacks.size(), 6);
    for (int i = 0; i < singlePartMIMEReaderCallbacks.size(); i++) {
        //Actual

        final SinglePartMIMEDrainReaderCallbackImpl currentCallback = singlePartMIMEReaderCallbacks.get(i);
        //Expected

        final BodyPart currentExpectedPart = _currentMimeMultipartBody.getBodyPart(i);
        //Construct expected headers and verify they match

        final Map<String, String> expectedHeaders = new HashMap<String, String>();
        @SuppressWarnings("unchecked") final Enumeration<Header> allHeaders = currentExpectedPart.getAllHeaders();
        while (allHeaders.hasMoreElements()) {
            final Header header = allHeaders.nextElement();
            expectedHeaders.put(header.getName(), header.getValue());
        }
        Assert.assertEquals(currentCallback.getHeaders(), expectedHeaders);
        //Verify that the bodies are empty
        Assert.assertNull(currentCallback.getFinishedData());
    }
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) Header(javax.mail.Header) HashMap(java.util.HashMap) ByteString(com.linkedin.data.ByteString) Test(org.testng.annotations.Test)

Aggregations

BodyPart (javax.mail.BodyPart)77 MimeMultipart (javax.mail.internet.MimeMultipart)57 MimeBodyPart (javax.mail.internet.MimeBodyPart)46 MessagingException (javax.mail.MessagingException)23 MimeMessage (javax.mail.internet.MimeMessage)21 Multipart (javax.mail.Multipart)16 Header (javax.mail.Header)15 IOException (java.io.IOException)14 DispositionNotification (com.sun.mail.dsn.DispositionNotification)13 HashMap (java.util.HashMap)13 DataHandler (javax.activation.DataHandler)13 InternetHeaders (javax.mail.internet.InternetHeaders)13 ByteString (com.linkedin.data.ByteString)12 Test (org.testng.annotations.Test)10 FileDataSource (javax.activation.FileDataSource)9 Session (javax.mail.Session)9 InternetAddress (javax.mail.internet.InternetAddress)8 Properties (java.util.Properties)7 File (java.io.File)6 InputStream (java.io.InputStream)6