Search in sources :

Example 1 with Multipart

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

the class MailSendingMessageHandlerContextTests method byteArrayMessage.

@Test
public void byteArrayMessage() throws Exception {
    byte[] payload = { 1, 2, 3 };
    org.springframework.messaging.Message<?> message = MessageBuilder.withPayload(payload).setHeader(MailHeaders.ATTACHMENT_FILENAME, "attachment.txt").setHeader(MailHeaders.TO, MailTestsHelper.TO).build();
    this.handler.handleMessage(message);
    assertThat(this.mailSender.getSentMimeMessages().size()).as("no mime message should have been sent").isEqualTo(1);
    assertThat(this.mailSender.getSentSimpleMailMessages().size()).as("only one simple message must be sent").isEqualTo(0);
    byte[] buffer = new byte[1024];
    MimeMessage mimeMessage = this.mailSender.getSentMimeMessages().get(0);
    assertThat(mimeMessage.getContent() instanceof Multipart).as("message must be multipart").isTrue();
    int size = new DataInputStream(((Multipart) mimeMessage.getContent()).getBodyPart(0).getInputStream()).read(buffer);
    assertThat(size).as("buffer size does not match").isEqualTo(payload.length);
    byte[] messageContent = new byte[size];
    System.arraycopy(buffer, 0, messageContent, 0, payload.length);
    assertThat(messageContent).as("buffer content does not match").isEqualTo(payload);
    assertThat(MailTestsHelper.TO.length).isEqualTo(mimeMessage.getRecipients(Message.RecipientType.TO).length);
}
Also used : Multipart(jakarta.mail.Multipart) MimeMessage(jakarta.mail.internet.MimeMessage) DataInputStream(java.io.DataInputStream) Test(org.junit.jupiter.api.Test)

Example 2 with Multipart

use of jakarta.mail.Multipart in project triplea by triplea-game.

the class DefaultEmailSender method sendEmail.

@Override
public void sendEmail(final String subject, final String htmlMessage, final Path saveGame, final String saveGameName) throws IOException {
    // this is the last step and we create the email to send
    final Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    if (encrypted) {
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.starttls.required", "true");
    }
    props.put("mail.smtp.host", emailServerHost);
    props.put("mail.smtp.port", emailServerPort);
    props.put("mail.smtp.connectiontimeout", TIMEOUT);
    props.put("mail.smtp.timeout", TIMEOUT);
    // todo get the turn and player number from the game data
    try {
        final Session session = Session.getInstance(props, null);
        final MimeMessage mimeMessage = new MimeMessage(session);
        // Build the message fields one by one:
        // priority
        mimeMessage.setHeader("X-Priority", "3 (Normal)");
        // from
        mimeMessage.setFrom(new InternetAddress(username));
        // to address
        for (final String token : Splitter.on(' ').omitEmptyStrings().trimResults().split(toAddress)) {
            mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(token));
        }
        // subject
        mimeMessage.setSubject(subjectPrefix + " " + subject);
        final MimeBodyPart bodypart = new MimeBodyPart();
        bodypart.setText(htmlMessage, "UTF-8");
        bodypart.setHeader("Content-Type", "text/html");
        if (saveGame != null) {
            final Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(bodypart);
            // add save game
            try (InputStream fin = Files.newInputStream(saveGame)) {
                final DataSource source = new ByteArrayDataSource(fin, "application/triplea");
                final BodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName(saveGameName);
                multipart.addBodyPart(messageBodyPart);
            }
            mimeMessage.setContent(multipart);
        }
        // date
        try {
            mimeMessage.setSentDate(Date.from(Instant.now()));
        } catch (final Exception e) {
        // NoOp - the Date field is simply ignored in this case
        }
        try (Transport transport = session.getTransport("smtp")) {
            transport.connect(emailServerHost, emailServerPort, username, password);
            mimeMessage.saveChanges();
            transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        }
    } catch (final MessagingException e) {
        throw new IOException(e);
    }
}
Also used : MimeBodyPart(jakarta.mail.internet.MimeBodyPart) BodyPart(jakarta.mail.BodyPart) InternetAddress(jakarta.mail.internet.InternetAddress) Multipart(jakarta.mail.Multipart) MimeMultipart(jakarta.mail.internet.MimeMultipart) MessagingException(jakarta.mail.MessagingException) InputStream(java.io.InputStream) DataHandler(jakarta.activation.DataHandler) IOException(java.io.IOException) Properties(java.util.Properties) IOException(java.io.IOException) MessagingException(jakarta.mail.MessagingException) ByteArrayDataSource(jakarta.mail.util.ByteArrayDataSource) DataSource(jakarta.activation.DataSource) MimeMessage(jakarta.mail.internet.MimeMessage) MimeMultipart(jakarta.mail.internet.MimeMultipart) MimeBodyPart(jakarta.mail.internet.MimeBodyPart) Transport(jakarta.mail.Transport) ByteArrayDataSource(jakarta.mail.util.ByteArrayDataSource) Session(jakarta.mail.Session)

Example 3 with Multipart

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

the class MimeMessageParser method parseMimePartTree.

private static void parseMimePartTree(@NotNull final MimePart currentPart, @NotNull final ParsedMimeMessageComponents parsedComponents, final boolean fetchAttachmentData) {
    for (final Header header : retrieveAllHeaders(currentPart)) {
        parseHeader(header, parsedComponents);
    }
    final String disposition = parseDisposition(currentPart);
    if (isMimeType(currentPart, "text/plain") && !Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
        parsedComponents.plainContent.append((Object) parseContent(currentPart));
    } else if (isMimeType(currentPart, "text/html") && !Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
        parsedComponents.htmlContent.append((Object) parseContent(currentPart));
    } else if (isMimeType(currentPart, "text/calendar") && parsedComponents.calendarContent == null && !Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
        parsedComponents.calendarContent = parseCalendarContent(currentPart);
        parsedComponents.calendarMethod = parseCalendarMethod(currentPart);
    } else if (isMimeType(currentPart, "multipart/*")) {
        final Multipart mp = parseContent(currentPart);
        for (int i = 0, count = countBodyParts(mp); i < count; i++) {
            parseMimePartTree(getBodyPartAtIndex(mp, i), parsedComponents, fetchAttachmentData);
        }
    } else {
        final DataSource ds = createDataSource(currentPart, fetchAttachmentData);
        // if the diposition is not provided, for now the part should be treated as inline (later non-embedded inline attachments are moved)
        if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
            parsedComponents.attachmentList.add(new SimpleEntry<>(parseResourceNameOrUnnamed(parseContentID(currentPart), parseFileName(currentPart)), ds));
        } else if (disposition == null || Part.INLINE.equalsIgnoreCase(disposition)) {
            if (parseContentID(currentPart) != null) {
                parsedComponents.cidMap.put(parseContentID(currentPart), ds);
            } else {
                // contentID missing -> treat as standard attachment
                parsedComponents.attachmentList.add(new SimpleEntry<>(parseResourceNameOrUnnamed(null, parseFileName(currentPart)), ds));
            }
        } else {
            throw new IllegalStateException("invalid attachment type");
        }
    }
}
Also used : Multipart(jakarta.mail.Multipart) Header(jakarta.mail.Header) SimpleEntry(java.util.AbstractMap.SimpleEntry) DataSource(jakarta.activation.DataSource) ByteArrayDataSource(jakarta.mail.util.ByteArrayDataSource) NamedDataSource(org.simplejavamail.internal.util.NamedDataSource)

Example 4 with Multipart

use of jakarta.mail.Multipart in project easy-smpc by prasser.

the class ConnectionIMAP method send.

@Override
protected void send(String recipient, String subject, String body, Object attachment) throws BusException {
    synchronized (propertiesSending) {
        // Make sure we are ready to go
        if (sessionSending == null) {
            sessionSending = Session.getInstance(propertiesSending, null);
        }
        try {
            // Create message
            MimeMessage email = new MimeMessage(sessionSending);
            // Add sender and recipient
            email.setRecipient(RecipientType.TO, new InternetAddress(recipient));
            email.setSender(new InternetAddress(getSendingEmailAddress()));
            email.setFrom(new InternetAddress(getSendingEmailAddress()));
            email.setSubject(subject);
            // Add body
            MimeBodyPart mimeBodyPart = new MimeBodyPart();
            mimeBodyPart.setDisposition(MimeBodyPart.INLINE);
            mimeBodyPart.setContent(body, "text/plain");
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(mimeBodyPart);
            // Add attachment
            long attachmentSize = 0;
            if (attachment != null) {
                mimeBodyPart = new MimeBodyPart();
                mimeBodyPart.setDisposition(MimeBodyPart.ATTACHMENT);
                byte[] attachmentBytes = getByteArrayOutputStream(attachment);
                mimeBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(attachmentBytes, "application/octet-stream")));
                mimeBodyPart.setFileName(FILENAME_MESSAGE);
                multipart.addBodyPart(mimeBodyPart);
                attachmentSize = attachmentBytes.length;
            }
            // Compose message
            email.setContent(multipart);
            // Send
            Transport.send(email, getSendingUserName(), sendingPassword);
            if (listener != null) {
                listener.messageSent(attachmentSize);
            }
            LOGGER.debug("Message sent logged", new Date(), "Message sent", subject);
        } catch (Exception e) {
            throw new BusException("Unable to send message", e);
        }
    }
}
Also used : InternetAddress(jakarta.mail.internet.InternetAddress) Multipart(jakarta.mail.Multipart) MimeMultipart(jakarta.mail.internet.MimeMultipart) MimeMessage(jakarta.mail.internet.MimeMessage) MimeMultipart(jakarta.mail.internet.MimeMultipart) DataHandler(jakarta.activation.DataHandler) MimeBodyPart(jakarta.mail.internet.MimeBodyPart) ByteArrayDataSource(jakarta.mail.util.ByteArrayDataSource) BusException(org.bihealth.mi.easybus.BusException) Date(java.util.Date) MessagingException(jakarta.mail.MessagingException) IOException(java.io.IOException) BusException(org.bihealth.mi.easybus.BusException)

Example 5 with Multipart

use of jakarta.mail.Multipart 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)

Aggregations

Multipart (jakarta.mail.Multipart)17 MimeMessage (jakarta.mail.internet.MimeMessage)10 MimeBodyPart (jakarta.mail.internet.MimeBodyPart)8 MimeMultipart (jakarta.mail.internet.MimeMultipart)8 DataHandler (jakarta.activation.DataHandler)6 BodyPart (jakarta.mail.BodyPart)6 MessagingException (jakarta.mail.MessagingException)6 IOException (java.io.IOException)6 DataSource (jakarta.activation.DataSource)5 InternetAddress (jakarta.mail.internet.InternetAddress)5 ByteArrayDataSource (jakarta.mail.util.ByteArrayDataSource)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 Date (java.util.Date)4 InputStream (java.io.InputStream)3 Header (jakarta.mail.Header)2 Part (jakarta.mail.Part)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 DataInputStream (java.io.DataInputStream)2 ByteArrayDataSource (org.apache.openmeetings.util.mail.ByteArrayDataSource)2 Test (org.junit.jupiter.api.Test)2