Search in sources :

Example 6 with BodyPart

use of jakarta.mail.BodyPart in project greenmail by greenmail-mail-test.

the class Pop3ServerTest method testRetrieveMultipart.

@Test
public void testRetrieveMultipart() throws Exception {
    assertThat(greenMail.getPop3()).isNotNull();
    String subject = GreenMailUtil.random();
    String body = GreenMailUtil.random();
    String to = "test@localhost";
    GreenMailUtil.sendAttachmentEmail(to, "from@localhost", subject, body, new byte[] { 0, 1, 2 }, "image/gif", "testimage_filename", "testimage_description", ServerSetupTest.SMTP);
    greenMail.waitForIncomingEmail(5000, 1);
    try (Retriever retriever = new Retriever(greenMail.getPop3())) {
        Message[] messages = retriever.getMessages(to);
        Object o = messages[0].getContent();
        assertThat(o instanceof MimeMultipart).isTrue();
        MimeMultipart mp = (MimeMultipart) o;
        assertThat(mp.getCount()).isEqualTo(2);
        BodyPart bp;
        bp = mp.getBodyPart(0);
        assertThat(GreenMailUtil.getBody(bp).trim()).isEqualTo(body);
        bp = mp.getBodyPart(1);
        assertThat(GreenMailUtil.getBody(bp).trim()).isEqualTo("AAEC");
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        GreenMailUtil.copyStream(bp.getInputStream(), bout);
        byte[] gif = bout.toByteArray();
        for (int i = 0; i < gif.length; i++) {
            assertThat((int) gif[i]).isEqualTo(i);
        }
    }
}
Also used : BodyPart(jakarta.mail.BodyPart) Retriever(com.icegreen.greenmail.util.Retriever) Message(jakarta.mail.Message) MimeMultipart(jakarta.mail.internet.MimeMultipart) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Test(org.junit.Test) ServerSetupTest(com.icegreen.greenmail.util.ServerSetupTest)

Example 7 with BodyPart

use of jakarta.mail.BodyPart in project spring-integration-samples by spring-projects.

the class EmailParserUtils method handleMultipart.

/**
 * Parses any {@link Multipart} instances that contain text or Html attachments,
 * {@link InputStream} instances, additional instances of {@link Multipart}
 * or other attached instances of {@link jakarta.mail.Message}.
 *
 * Will create the respective {@link EmailFragment}s representing those attachments.
 *
 * Instances of {@link jakarta.mail.Message} are delegated to
 * {@link #handleMessage(File, jakarta.mail.Message, List)}. Further instances
 * of {@link Multipart} are delegated to
 * {@link #handleMultipart(File, Multipart, jakarta.mail.Message, List)}.
 *
 * @param directory Must not be null
 * @param multipart Must not be null
 * @param mailMessage Must not be null
 * @param emailFragments Must not be null
 */
public static void handleMultipart(File directory, Multipart multipart, jakarta.mail.Message mailMessage, List<EmailFragment> emailFragments) {
    Assert.notNull(directory, "The directory must not be null.");
    Assert.notNull(multipart, "The multipart object to be parsed must not be null.");
    Assert.notNull(mailMessage, "The mail message to be parsed must not be null.");
    Assert.notNull(emailFragments, "The collection of emailfragments must not be null.");
    final int count;
    try {
        count = multipart.getCount();
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info(String.format("Number of enclosed BodyPart objects: %s.", count));
        }
    } catch (MessagingException e) {
        throw new IllegalStateException("Error while retrieving the number of enclosed BodyPart objects.", e);
    }
    for (int i = 0; i < count; i++) {
        final BodyPart bp;
        try {
            bp = multipart.getBodyPart(i);
        } catch (MessagingException e) {
            throw new IllegalStateException("Error while retrieving body part.", e);
        }
        final String contentType;
        String filename;
        final String disposition;
        final String subject;
        try {
            contentType = bp.getContentType();
            filename = bp.getFileName();
            disposition = bp.getDisposition();
            subject = mailMessage.getSubject();
            if (filename == null && bp instanceof MimeBodyPart) {
                filename = ((MimeBodyPart) bp).getContentID();
            }
        } catch (MessagingException e) {
            throw new IllegalStateException("Unable to retrieve body part meta data.", e);
        }
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info(String.format("BodyPart - Content Type: '%s', filename: '%s', disposition: '%s', subject: '%s'", new Object[] { contentType, filename, disposition, subject }));
        }
        if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
            LOGGER.info(String.format("Handdling attachment '%s', type: '%s'", filename, contentType));
        }
        final Object content;
        try {
            content = bp.getContent();
        } catch (IOException e) {
            throw new IllegalStateException("Error while retrieving the email contents.", e);
        } catch (MessagingException e) {
            throw new IllegalStateException("Error while retrieving the email contents.", e);
        }
        if (content instanceof String) {
            if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
                emailFragments.add(new EmailFragment(directory, i + "-" + filename, content));
                LOGGER.info(String.format("Handdling attachment '%s', type: '%s'", filename, contentType));
            } else {
                final String textFilename;
                final ContentType ct;
                try {
                    ct = new ContentType(contentType);
                } catch (ParseException e) {
                    throw new IllegalStateException("Error while parsing content type '" + contentType + "'.", e);
                }
                if ("text/plain".equalsIgnoreCase(ct.getBaseType())) {
                    textFilename = "message.txt";
                } else if ("text/html".equalsIgnoreCase(ct.getBaseType())) {
                    textFilename = "message.html";
                } else {
                    textFilename = "message.other";
                }
                emailFragments.add(new EmailFragment(directory, textFilename, content));
            }
        } else if (content instanceof InputStream) {
            final InputStream inputStream = (InputStream) content;
            final ByteArrayOutputStream bis = new ByteArrayOutputStream();
            try {
                IOUtils.copy(inputStream, bis);
            } catch (IOException e) {
                throw new IllegalStateException("Error while copying input stream to the ByteArrayOutputStream.", e);
            }
            emailFragments.add(new EmailFragment(directory, filename, bis.toByteArray()));
        } else if (content instanceof jakarta.mail.Message) {
            handleMessage(directory, (jakarta.mail.Message) content, emailFragments);
        } else if (content instanceof Multipart) {
            final Multipart mp2 = (Multipart) content;
            handleMultipart(directory, mp2, mailMessage, emailFragments);
        } else {
            throw new IllegalStateException("Content type not handled: " + content.getClass().getSimpleName());
        }
    }
}
Also used : MimeBodyPart(jakarta.mail.internet.MimeBodyPart) BodyPart(jakarta.mail.BodyPart) Multipart(jakarta.mail.Multipart) ContentType(jakarta.mail.internet.ContentType) MessagingException(jakarta.mail.MessagingException) InputStream(java.io.InputStream) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ParseException(jakarta.mail.internet.ParseException) MimeBodyPart(jakarta.mail.internet.MimeBodyPart)

Example 8 with BodyPart

use of jakarta.mail.BodyPart in project openmeetings by apache.

the class TestSendIcalMessage method sendIcalMessage.

private void sendIcalMessage(byte[] iCalMimeBody) throws Exception {
    log.debug("sendIcalMessage");
    // Building MimeMessage
    MimeMessage mimeMessage = mailHandler.getBasicMimeMessage();
    mimeMessage.setSubject(subject);
    mimeMessage.addRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients, false));
    // -- Create a new message --
    BodyPart msg = new MimeBodyPart();
    msg.setDataHandler(new DataHandler(new ByteArrayDataSource(htmlBody, "text/html; charset=\"utf-8\"")));
    Multipart multipart = new MimeMultipart();
    BodyPart iCalAttachment = new MimeBodyPart();
    iCalAttachment.setDataHandler(new DataHandler(new jakarta.mail.util.ByteArrayDataSource(new ByteArrayInputStream(iCalMimeBody), "text/calendar;method=REQUEST;charset=\"UTF-8\"")));
    iCalAttachment.setFileName("invite.ics");
    multipart.addBodyPart(iCalAttachment);
    multipart.addBodyPart(msg);
    mimeMessage.setSentDate(new Date());
    mimeMessage.setContent(multipart);
    assertNotNull(mimeMessage, "Valid MIME message should be created");
}
Also used : MimeBodyPart(jakarta.mail.internet.MimeBodyPart) BodyPart(jakarta.mail.BodyPart) Multipart(jakarta.mail.Multipart) MimeMultipart(jakarta.mail.internet.MimeMultipart) MimeMessage(jakarta.mail.internet.MimeMessage) MimeMultipart(jakarta.mail.internet.MimeMultipart) ByteArrayInputStream(java.io.ByteArrayInputStream) DataHandler(jakarta.activation.DataHandler) MimeBodyPart(jakarta.mail.internet.MimeBodyPart) ByteArrayDataSource(org.apache.openmeetings.util.mail.ByteArrayDataSource) Date(java.util.Date)

Example 9 with BodyPart

use of jakarta.mail.BodyPart in project openmeetings by apache.

the class MailHandler method appendIcsBody.

protected MimeMessage appendIcsBody(MimeMessage msg, MailMessage m) throws Exception {
    log.debug("setMessageBody for iCal message");
    // -- Create a new message --
    Multipart multipart = new MimeMultipart();
    Multipart multiBody = new MimeMultipart("alternative");
    BodyPart html = new MimeBodyPart();
    html.setDataHandler(new DataHandler(new ByteArrayDataSource(m.getBody(), "text/html; charset=UTF-8")));
    multiBody.addBodyPart(html);
    BodyPart iCalContent = new MimeBodyPart();
    iCalContent.addHeader("content-class", "urn:content-classes:calendarmessage");
    iCalContent.setDataHandler(new DataHandler(new ByteArrayDataSource(new ByteArrayInputStream(m.getIcs()), "text/calendar; charset=UTF-8; method=" + m.getIcsMethod())));
    multiBody.addBodyPart(iCalContent);
    BodyPart body = new MimeBodyPart();
    body.setContent(multiBody);
    multipart.addBodyPart(body);
    BodyPart iCalAttachment = new MimeBodyPart();
    iCalAttachment.setDataHandler(new DataHandler(new ByteArrayDataSource(new ByteArrayInputStream(m.getIcs()), "application/ics")));
    iCalAttachment.removeHeader("Content-Transfer-Encoding");
    iCalAttachment.addHeader("Content-Transfer-Encoding", "base64");
    iCalAttachment.removeHeader("Content-Type");
    iCalAttachment.addHeader("Content-Type", "application/ics");
    iCalAttachment.setFileName("invite.ics");
    multipart.addBodyPart(iCalAttachment);
    msg.setContent(multipart);
    return msg;
}
Also used : BodyPart(jakarta.mail.BodyPart) MimeBodyPart(jakarta.mail.internet.MimeBodyPart) Multipart(jakarta.mail.Multipart) MimeMultipart(jakarta.mail.internet.MimeMultipart) MimeMultipart(jakarta.mail.internet.MimeMultipart) ByteArrayInputStream(java.io.ByteArrayInputStream) DataHandler(jakarta.activation.DataHandler) MimeBodyPart(jakarta.mail.internet.MimeBodyPart) ByteArrayDataSource(org.apache.openmeetings.util.mail.ByteArrayDataSource)

Example 10 with BodyPart

use of jakarta.mail.BodyPart in project simple-java-mail by bbottema.

the class MimeMessageHelper method configureForwarding.

/**
 * If provided, adds the {@code emailToForward} as a MimeBodyPart to the mixed multipart root.
 * <p>
 * <strong>Note:</strong> this is done without setting {@code Content-Disposition} so email clients can choose
 * how to display embedded forwards. Most client will show the forward as inline, some may show it as attachment.
 */
static void configureForwarding(@NotNull final Email email, @NotNull final MimeMultipart multipartRootMixed) throws MessagingException {
    if (email.getEmailToForward() != null) {
        final BodyPart fordwardedMessage = new MimeBodyPart();
        fordwardedMessage.setContent(email.getEmailToForward(), "message/rfc822");
        multipartRootMixed.addBodyPart(fordwardedMessage);
    }
}
Also used : BodyPart(jakarta.mail.BodyPart) MimeBodyPart(jakarta.mail.internet.MimeBodyPart) MimeBodyPart(jakarta.mail.internet.MimeBodyPart)

Aggregations

BodyPart (jakarta.mail.BodyPart)16 MimeMultipart (jakarta.mail.internet.MimeMultipart)11 MimeBodyPart (jakarta.mail.internet.MimeBodyPart)8 DataHandler (jakarta.activation.DataHandler)6 Multipart (jakarta.mail.Multipart)6 MimeMessage (jakarta.mail.internet.MimeMessage)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 InputStream (java.io.InputStream)4 Test (org.junit.Test)4 Message (jakarta.mail.Message)3 MessagingException (jakarta.mail.MessagingException)3 Retriever (com.icegreen.greenmail.util.Retriever)2 ServerSetupTest (com.icegreen.greenmail.util.ServerSetupTest)2 DataSource (jakarta.activation.DataSource)2 ContentType (jakarta.mail.internet.ContentType)2 ParameterList (jakarta.mail.internet.ParameterList)2 ByteArrayDataSource (jakarta.mail.util.ByteArrayDataSource)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 IOException (java.io.IOException)2 ByteArrayDataSource (org.apache.openmeetings.util.mail.ByteArrayDataSource)2