Search in sources :

Example 11 with BodyPart

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

the class MimeMessageHelper method getBodyPartFromDatasource.

/**
 * Helper method which generates a {@link BodyPart} from an {@link AttachmentResource} (from its {@link DataSource}) and a disposition type
 * ({@link Part#INLINE} or {@link Part#ATTACHMENT}). With this the attachment data can be converted into objects that fit in the email structure.
 * <p>
 * For every attachment and embedded image a header needs to be set.
 *
 * @param attachmentResource An object that describes the attachment and contains the actual content data.
 * @param dispositionType    The type of attachment, {@link Part#INLINE} or {@link Part#ATTACHMENT} .
 *
 * @return An object with the attachment data read for placement in the email structure.
 * @throws MessagingException All BodyPart setters.
 */
private static BodyPart getBodyPartFromDatasource(final AttachmentResource attachmentResource, final String dispositionType) throws MessagingException {
    final BodyPart attachmentPart = new MimeBodyPart();
    // setting headers isn't working nicely using the javax mail API, so let's do that manually
    final String resourceName = determineResourceName(attachmentResource, true);
    final String fileName = determineResourceName(attachmentResource, false);
    attachmentPart.setDataHandler(new DataHandler(new NamedDataSource(fileName, attachmentResource.getDataSource())));
    attachmentPart.setFileName(fileName);
    final String contentType = attachmentResource.getDataSource().getContentType();
    ParameterList pl = new ParameterList();
    pl.set("filename", fileName);
    pl.set("name", fileName);
    attachmentPart.setHeader("Content-Type", contentType + pl);
    attachmentPart.setHeader("Content-ID", format("<%s>", resourceName));
    attachmentPart.setDisposition(dispositionType);
    return attachmentPart;
}
Also used : BodyPart(jakarta.mail.BodyPart) MimeBodyPart(jakarta.mail.internet.MimeBodyPart) ParameterList(jakarta.mail.internet.ParameterList) DataHandler(jakarta.activation.DataHandler) MimeBodyPart(jakarta.mail.internet.MimeBodyPart) NamedDataSource(org.simplejavamail.internal.util.NamedDataSource)

Example 12 with BodyPart

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

the class SimpleMessageAttributes method parseMimePart.

/**
 * Parses key data items from a MimeMessage for seperate storage.
 * TODO this is a mess, and should be completely revamped.
 */
void parseMimePart(MimePart part) {
    final String body = GreenMailUtil.getBody(part);
    size = body.length();
    // Section 1 - Message Headers
    if (part instanceof MimeMessage) {
        try {
            String[] subjects = part.getHeader("Subject");
            if ((subjects != null) && (subjects.length > 0)) {
                subject = subjects[0];
            }
        } catch (MessagingException me) {
        // if (DEBUG) getLogger().debug("Messaging Exception for getSubject: " + me);
        }
    }
    try {
        from = part.getHeader("From");
    } catch (MessagingException me) {
    // if (DEBUG) getLogger().debug("Messaging Exception for getHeader(From): " + me);
    }
    try {
        sender = part.getHeader("Sender");
    } catch (MessagingException me) {
    // if (DEBUG) getLogger().debug("Messaging Exception for getHeader(Sender): " + me);
    }
    try {
        replyTo = part.getHeader("Reply-To");
    } catch (MessagingException me) {
    // if (DEBUG) getLogger().debug("Messaging Exception for getHeader(Reply To): " + me);
    }
    try {
        to = part.getHeader("To");
    } catch (MessagingException me) {
    // if (DEBUG) getLogger().debug("Messaging Exception for getHeader(To): " + me);
    }
    try {
        cc = part.getHeader("Cc");
    } catch (MessagingException me) {
    // if (DEBUG) getLogger().debug("Messaging Exception for getHeader(To): " + me);
    }
    try {
        bcc = part.getHeader("Bcc");
    } catch (MessagingException me) {
    // if (DEBUG) getLogger().debug("Messaging Exception for getHeader(To): " + me);
    }
    try {
        inReplyTo = part.getHeader("In Reply To");
    } catch (MessagingException me) {
    // if (DEBUG) getLogger().debug("Messaging Exception for getHeader(In Reply To): " + me);
    }
    try {
        date = part.getHeader("Date");
    } catch (MessagingException me) {
    // if (DEBUG) getLogger().debug("Messaging Exception for getHeader(Date): " + me);
    }
    try {
        messageID = part.getHeader("Message-ID");
    } catch (MessagingException me) {
    // if (DEBUG) getLogger().debug("Messaging Exception for getHeader(messageID): " + me);
    }
    String contentTypeLine = null;
    try {
        contentTypeLine = part.getContentType();
    } catch (MessagingException me) {
    // if (DEBUG) getLogger().debug("Messaging Exception for getContentType(): " + me);
    }
    if (contentTypeLine != null) {
        decodeContentType(contentTypeLine);
    }
    try {
        contentID = part.getContentID();
    } catch (MessagingException me) {
    // if (DEBUG) getLogger().debug("Messaging Exception for getContentUD(): " + me);
    }
    try {
        contentDesc = part.getDescription();
    } catch (MessagingException me) {
    // if (DEBUG) getLogger().debug("Messaging Exception for getDescription(): " + me);
    }
    try {
        contentEncoding = part.getEncoding();
        // default value.
        if (contentEncoding == null) {
            contentEncoding = "7BIT";
        }
    } catch (MessagingException me) {
    // if (DEBUG) getLogger().debug("Messaging Exception for getEncoding(): " + me);
    }
    try {
        // contentDisposition = part.getDisposition();
        contentDisposition = Header.create(part.getHeader("Content-Disposition"));
    } catch (MessagingException me) {
        if (log.isDebugEnabled()) {
            log.debug("Can not create content disposition for part " + part, me);
        }
    }
    try {
        // TODO this doesn't work
        lineCount = GreenMailUtil.getLineCount(body);
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Can not get line count for part " + part, e);
        }
    }
    // Recurse through any embedded parts
    if (primaryType.equalsIgnoreCase(MULTIPART)) {
        MimeMultipart container;
        try {
            container = (MimeMultipart) part.getContent();
            int count = container.getCount();
            parts = new SimpleMessageAttributes[count];
            for (int i = 0; i < count; i++) {
                BodyPart nextPart = container.getBodyPart(i);
                if (nextPart instanceof MimePart) {
                    SimpleMessageAttributes partAttrs = new SimpleMessageAttributes(null, receivedDate);
                    partAttrs.parseMimePart((MimePart) nextPart);
                    parts[i] = partAttrs;
                }
            }
        } catch (Exception e) {
            if (log.isDebugEnabled()) {
                log.debug("Can not recurse through multipart content", e);
            }
        }
    } else if (primaryType.equalsIgnoreCase("message")) {
        if (secondaryType.equalsIgnoreCase("RFC822")) {
            parts = new SimpleMessageAttributes[1];
            try {
                MimeMessage wrappedMessage = (MimeMessage) part.getContent();
                if (log.isDebugEnabled()) {
                    log.debug("message type : " + wrappedMessage.getContentType());
                }
                parts[0] = new SimpleMessageAttributes(wrappedMessage, null);
            } catch (Exception e) {
                throw new IllegalStateException("Can not extract part for " + primaryType + "/" + secondaryType, e);
            }
        } else {
            log.warn("Unknown/unhandled subtype {} of message encountered.", secondaryType);
        }
    }
}
Also used : BodyPart(jakarta.mail.BodyPart) MessagingException(jakarta.mail.MessagingException) MessagingException(jakarta.mail.MessagingException)

Example 13 with BodyPart

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

the class SmtpServerTest method testSmtpServerReceiveMultipart.

@Test
public void testSmtpServerReceiveMultipart() throws Exception {
    assertThat(greenMail.getReceivedMessages().length).isEqualTo(0);
    String subject = GreenMailUtil.random();
    String body = GreenMailUtil.random();
    GreenMailUtil.sendAttachmentEmail("test@localhost", "from@localhost", subject, body, new byte[] { 0, 1, 2 }, "image/gif", "testimage_filename", "testimage_description", ServerSetupTest.SMTP);
    greenMail.waitForIncomingEmail(1500, 1);
    Message[] emails = greenMail.getReceivedMessages();
    assertThat(emails.length).isEqualTo(1);
    assertThat(emails[0].getSubject()).isEqualTo(subject);
    Object o = emails[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++) {
        // AssertEquals used to convert both the arguments to Long /
        assertThat((int) gif[i]).isEqualTo(i);
    }
}
Also used : BodyPart(jakarta.mail.BodyPart) Message(jakarta.mail.Message) MimeMessage(jakarta.mail.internet.MimeMessage) MimeMultipart(jakarta.mail.internet.MimeMultipart) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Test(org.junit.Test) ServerSetupTest(com.icegreen.greenmail.util.ServerSetupTest)

Example 14 with BodyPart

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

the class FetchCommand method handleBodyFetch.

private void handleBodyFetch(MimeMessage mimeMessage, String sectionSpecifier, Partial partial, StringBuilder response) throws IOException, MessagingException {
    if (log.isDebugEnabled()) {
        log.debug("Fetching body part for section specifier {} and mime message (contentType={})", sectionSpecifier, mimeMessage.getContentType());
    }
    if (sectionSpecifier.length() == 0) {
        // TODO - need to use an InputStream from the response here.
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        mimeMessage.writeTo(bout);
        byte[] bytes = bout.toByteArray();
        bytes = doPartial(partial, bytes, response);
        addLiteral(bytes, response);
    } else if ("HEADER".equalsIgnoreCase(sectionSpecifier)) {
        Enumeration<?> inum = mimeMessage.getAllHeaderLines();
        addHeaders(inum, response, partial);
    } else if (sectionSpecifier.startsWith("HEADER.FIELDS.NOT")) {
        String[] excludeNames = extractHeaderList(sectionSpecifier, "HEADER.FIELDS.NOT".length());
        Enumeration<?> inum = mimeMessage.getNonMatchingHeaderLines(excludeNames);
        addHeaders(inum, response, partial);
    } else if (sectionSpecifier.startsWith("HEADER.FIELDS ")) {
        String[] includeNames = extractHeaderList(sectionSpecifier, "HEADER.FIELDS ".length());
        Enumeration<?> inum = mimeMessage.getMatchingHeaderLines(includeNames);
        addHeaders(inum, response, partial);
    } else if (sectionSpecifier.endsWith("MIME")) {
        String[] strs = sectionSpecifier.trim().split("\\.");
        int partNumber = Integer.parseInt(strs[0]) - 1;
        MimeMultipart mp = (MimeMultipart) mimeMessage.getContent();
        byte[] bytes = GreenMailUtil.getHeaderAsBytes(mp.getBodyPart(partNumber));
        bytes = doPartial(partial, bytes, response);
        addLiteral(bytes, response);
    } else if ("TEXT".equalsIgnoreCase(sectionSpecifier)) {
        handleBodyFetchForText(mimeMessage, partial, response);
    } else {
        Object content = mimeMessage.getContent();
        if (content instanceof String) {
            handleBodyFetchForText(mimeMessage, partial, response);
        } else {
            MimeMultipart mp = (MimeMultipart) content;
            BodyPart part = null;
            // Find part by number spec, eg "1" or "2.1" or "4.3.1" ...
            String spec = sectionSpecifier;
            int dotIdx = spec.indexOf('.');
            String pre = dotIdx < 0 ? spec : spec.substring(0, dotIdx);
            while (null != pre && NUMBER_MATCHER.matcher(pre).matches()) {
                int partNumber = Integer.parseInt(pre) - 1;
                if (null == part) {
                    part = mp.getBodyPart(partNumber);
                } else {
                    // Content must be multipart
                    part = ((Multipart) part.getContent()).getBodyPart(partNumber);
                }
                dotIdx = spec.indexOf('.');
                if (dotIdx > 0) {
                    // Another sub part index?
                    spec = spec.substring(dotIdx + 1);
                    pre = spec.substring(0, dotIdx);
                } else {
                    pre = null;
                }
            }
            if (null == part) {
                throw new IllegalStateException("Got null for " + sectionSpecifier);
            }
            // A bit optimistic to only cover theses cases ... TODO
            if ("message/rfc822".equalsIgnoreCase(part.getContentType())) {
                handleBodyFetch((MimeMessage) part.getContent(), spec, partial, response);
            } else if ("TEXT".equalsIgnoreCase(spec)) {
                handleBodyFetchForText(mimeMessage, partial, response);
            } else {
                byte[] bytes = GreenMailUtil.getBodyAsBytes(part);
                bytes = doPartial(partial, bytes, response);
                addLiteral(bytes, response);
            }
        }
    }
}
Also used : BodyPart(jakarta.mail.BodyPart) Multipart(jakarta.mail.Multipart) MimeMultipart(jakarta.mail.internet.MimeMultipart) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MimeMultipart(jakarta.mail.internet.MimeMultipart) MimeMessage(jakarta.mail.internet.MimeMessage)

Example 15 with BodyPart

use of jakarta.mail.BodyPart in project mangooio by svenkubiak.

the class MailListener method setAttachments.

private void setAttachments(Mail mail, MimeMessage mimeMessage) throws MessagingException, IOException {
    if (mail.hasAttachments()) {
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(mail.getMessageText());
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        for (Path path : mail.getMessageAttachments()) {
            messageBodyPart = new MimeBodyPart();
            var filename = path.toRealPath().toString();
            DataSource source = new FileDataSource(filename);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(filename);
            multipart.addBodyPart(messageBodyPart);
        }
        mimeMessage.setContent(multipart);
    }
}
Also used : Path(java.nio.file.Path) BodyPart(jakarta.mail.BodyPart) MimeBodyPart(jakarta.mail.internet.MimeBodyPart) Multipart(jakarta.mail.Multipart) MimeMultipart(jakarta.mail.internet.MimeMultipart) MimeMultipart(jakarta.mail.internet.MimeMultipart) FileDataSource(jakarta.activation.FileDataSource) DataHandler(jakarta.activation.DataHandler) MimeBodyPart(jakarta.mail.internet.MimeBodyPart) FileDataSource(jakarta.activation.FileDataSource) DataSource(jakarta.activation.DataSource)

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