Search in sources :

Example 1 with BodyPart

use of jakarta.mail.BodyPart 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 2 with BodyPart

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

the class EMailServiceTest method testSendMailHTMLTemplate.

@Test
public void testSendMailHTMLTemplate() throws Exception {
    // prepare
    String eMailTemplateName = "email-html-template.vm";
    Map<String, String> mailTemplateProps = new HashMap<>();
    mailTemplateProps.put("name", "Jon Doe");
    String fromMail = "admin@localhost";
    String toEmail = "john@localhost.com";
    String subject = "Template HTML email!";
    Collection<String> toRecipients = new ArrayList<>();
    toRecipients.add(toEmail);
    EMail eMail = new EMail(MailType.MAIL_HTML, toRecipients, subject, "", Collections.emptyList(), Collections.emptyList());
    eMail.setMailFrom(fromMail);
    // test
    assertNull(eMail.getSentDate());
    eMailService.sendMail(eMail, eMailTemplateName, mailTemplateProps);
    assertNotNull(eMail.getSentDate());
    // fetch messages from server
    MimeMessage[] messages = mailServer.getReceivedMessages();
    assertNotNull(messages);
    assertEquals(1, messages.length);
    MimeMessage msg = messages[0];
    assertTrue(msg.getContentType().contains("multipart/mixed;"));
    assertEquals(subject, msg.getSubject());
    MimeMultipart message = (MimeMultipart) msg.getContent();
    BodyPart bodyPart = message.getBodyPart(0);
    assertEquals("text/html; charset=UTF-8", bodyPart.getHeader("Content-Type")[0]);
    String receivedMailContent = String.valueOf(bodyPart.getContent());
    assertTrue(receivedMailContent.contains("Dear Jon Doe"));
    assertTrue(receivedMailContent.contains("templated"));
    assertEquals(fromMail, msg.getFrom()[0].toString());
}
Also used : BodyPart(jakarta.mail.BodyPart) HashMap(java.util.HashMap) MimeMessage(jakarta.mail.internet.MimeMessage) MimeMultipart(jakarta.mail.internet.MimeMultipart) ArrayList(java.util.ArrayList) Test(org.junit.jupiter.api.Test)

Example 3 with BodyPart

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

the class MimeMessageParserTest method getBodyPartFromDatasource.

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 = "htgfiytityf.txt";
    final String fileName = "proper-name.txt";
    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 4 with BodyPart

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

the class MimeMessageHelperTest method filenameWithSpaceEncoding.

@Test
public void filenameWithSpaceEncoding() throws IOException, MessagingException {
    final String fileName = "file name.txt";
    final Email email = EmailHelper.createDummyEmailBuilder(true, true, false, false, false, false).clearAttachments().withAttachment(fileName, "abc".getBytes(), "text/plain").buildEmail();
    final MimeMessage mimeMessage = EmailConverter.emailToMimeMessage(email);
    final BodyPart bodyPart = ((MimeMultipart) mimeMessage.getContent()).getBodyPart(1);
    ContentType ct = new ContentType(bodyPart.getHeader("Content-Type")[0]);
    assertThat(ct.getParameter("filename")).isEqualTo(fileName);
    assertThat(bodyPart.getFileName()).isEqualTo(fileName);
}
Also used : BodyPart(jakarta.mail.BodyPart) Email(org.simplejavamail.api.email.Email) ContentType(jakarta.mail.internet.ContentType) MimeMessage(jakarta.mail.internet.MimeMessage) MimeMultipart(jakarta.mail.internet.MimeMultipart) Test(org.junit.Test)

Example 5 with BodyPart

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

the class LargeMessageTest method retrieveAndCheck.

/**
 * Retrieve message from retriever and check the attachment and text content
 *
 * @param server Server to read from
 * @param to     Account to retrieve
 */
private void retrieveAndCheck(AbstractServer server, String to) throws MessagingException, IOException {
    try (Retriever retriever = new Retriever(server)) {
        Message[] messages = retriever.getMessages(to);
        assertThat(messages.length).isEqualTo(1);
        Message message = messages[0];
        assertThat(message.getContentType().startsWith("multipart/mixed")).isTrue();
        MimeMultipart body = (MimeMultipart) message.getContent();
        assertThat(body.getContentType().startsWith("multipart/mixed")).isTrue();
        assertThat(body.getCount()).isEqualTo(2);
        // Message text
        final BodyPart textPart = body.getBodyPart(0);
        String text = (String) textPart.getContent();
        assertThat(text).isEqualTo(createLargeString());
        final BodyPart attachment = body.getBodyPart(1);
        assertThat(attachment.getContentType().equalsIgnoreCase("application/blubb; name=file")).isTrue();
        InputStream attachmentStream = (InputStream) attachment.getContent();
        byte[] bytes = toByteArray(attachmentStream);
        assertThat(bytes).isEqualTo(createLargeByteArray());
    }
}
Also used : BodyPart(jakarta.mail.BodyPart) Retriever(com.icegreen.greenmail.util.Retriever) Message(jakarta.mail.Message) MimeMultipart(jakarta.mail.internet.MimeMultipart) InputStream(java.io.InputStream)

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