Search in sources :

Example 6 with MimeMessage

use of jakarta.mail.internet.MimeMessage in project spring-framework by spring-projects.

the class JavaMailSenderTests method failedMimeMessage.

@Test
public void failedMimeMessage() throws MessagingException {
    MockJavaMailSender sender = new MockJavaMailSender();
    sender.setHost("host");
    sender.setUsername("username");
    sender.setPassword("password");
    MimeMessage mimeMessage1 = sender.createMimeMessage();
    mimeMessage1.setRecipient(Message.RecipientType.TO, new InternetAddress("he@mail.org"));
    mimeMessage1.setSubject("fail");
    MimeMessage mimeMessage2 = sender.createMimeMessage();
    mimeMessage2.setRecipient(Message.RecipientType.TO, new InternetAddress("she@mail.org"));
    try {
        sender.send(mimeMessage1, mimeMessage2);
    } catch (MailSendException ex) {
        ex.printStackTrace();
        assertThat(sender.transport.getConnectedHost()).isEqualTo("host");
        assertThat(sender.transport.getConnectedUsername()).isEqualTo("username");
        assertThat(sender.transport.getConnectedPassword()).isEqualTo("password");
        assertThat(sender.transport.isCloseCalled()).isTrue();
        assertThat(sender.transport.getSentMessages().size()).isEqualTo(1);
        assertThat(sender.transport.getSentMessage(0)).isEqualTo(mimeMessage2);
        assertThat(ex.getFailedMessages().size()).isEqualTo(1);
        assertThat(ex.getFailedMessages().keySet().iterator().next()).isEqualTo(mimeMessage1);
        Object subEx = ex.getFailedMessages().values().iterator().next();
        boolean condition = subEx instanceof MessagingException;
        assertThat(condition).isTrue();
        assertThat(((MessagingException) subEx).getMessage()).isEqualTo("failed");
    }
}
Also used : InternetAddress(jakarta.mail.internet.InternetAddress) MailSendException(org.springframework.mail.MailSendException) MimeMessage(jakarta.mail.internet.MimeMessage) MessagingException(jakarta.mail.MessagingException) Test(org.junit.jupiter.api.Test)

Example 7 with MimeMessage

use of jakarta.mail.internet.MimeMessage in project athenz by yahoo.

the class EmailNotificationService method getMimeMessage.

private MimeMessage getMimeMessage(String subject, String body, Collection<String> recipients, String from, byte[] logoImage) throws MessagingException {
    Session session = Session.getDefaultInstance(new Properties());
    // Create a new MimeMessage object.
    MimeMessage message = new MimeMessage(session);
    // Add subject, from and to lines.
    message.setSubject(subject, CHARSET_UTF_8);
    message.setFrom(new InternetAddress(from));
    message.setRecipients(jakarta.mail.Message.RecipientType.BCC, InternetAddress.parse(String.join(",", recipients)));
    // Set the HTML part.
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(body, "text/html; charset=" + CHARSET_UTF_8);
    // Create a multipart/mixed parent container.
    MimeMultipart msgParent = new MimeMultipart("related");
    // Add the body to the message.
    msgParent.addBodyPart(htmlPart);
    // Add the parent container to the message.
    message.setContent(msgParent);
    if (logoImage != null) {
        MimeBodyPart logo = new MimeBodyPart();
        logo.setContent(logoImage, "image/png");
        logo.setContentID(HTML_LOGO_CID_PLACEHOLDER);
        logo.setDisposition(Part.INLINE);
        // Add the attachment to the message.
        msgParent.addBodyPart(logo);
    }
    return message;
}
Also used : InternetAddress(jakarta.mail.internet.InternetAddress) MimeMessage(jakarta.mail.internet.MimeMessage) MimeMultipart(jakarta.mail.internet.MimeMultipart) MimeBodyPart(jakarta.mail.internet.MimeBodyPart) Session(jakarta.mail.Session)

Example 8 with MimeMessage

use of jakarta.mail.internet.MimeMessage in project gocd by gocd.

the class MailSession method createMessage.

public MimeMessage createMessage(String from, String to, String subject, String body) throws MessagingException {
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(from));
    msg.setRecipients(TO, to);
    msg.setSubject(subject);
    msg.setContent(msg, "text/plain");
    msg.setSentDate(new Date());
    msg.setText(body);
    msg.setSender(new InternetAddress(from));
    msg.setReplyTo(new InternetAddress[] { new InternetAddress(from) });
    return msg;
}
Also used : InternetAddress(jakarta.mail.internet.InternetAddress) MimeMessage(jakarta.mail.internet.MimeMessage) Date(java.util.Date)

Example 9 with MimeMessage

use of jakarta.mail.internet.MimeMessage in project spring-framework by spring-projects.

the class JavaMailSenderImpl method doSend.

/**
 * Actually send the given array of MimeMessages via JavaMail.
 * @param mimeMessages the MimeMessage objects to send
 * @param originalMessages corresponding original message objects
 * that the MimeMessages have been created from (with same array
 * length and indices as the "mimeMessages" array), if any
 * @throws org.springframework.mail.MailAuthenticationException
 * in case of authentication failure
 * @throws org.springframework.mail.MailSendException
 * in case of failure when sending a message
 */
protected void doSend(MimeMessage[] mimeMessages, @Nullable Object[] originalMessages) throws MailException {
    Map<Object, Exception> failedMessages = new LinkedHashMap<>();
    Transport transport = null;
    try {
        for (int i = 0; i < mimeMessages.length; i++) {
            // Check transport connection first...
            if (transport == null || !transport.isConnected()) {
                if (transport != null) {
                    try {
                        transport.close();
                    } catch (Exception ex) {
                    // Ignore - we're reconnecting anyway
                    }
                    transport = null;
                }
                try {
                    transport = connectTransport();
                } catch (AuthenticationFailedException ex) {
                    throw new MailAuthenticationException(ex);
                } catch (Exception ex) {
                    // Effectively, all remaining messages failed...
                    for (int j = i; j < mimeMessages.length; j++) {
                        Object original = (originalMessages != null ? originalMessages[j] : mimeMessages[j]);
                        failedMessages.put(original, ex);
                    }
                    throw new MailSendException("Mail server connection failed", ex, failedMessages);
                }
            }
            // Send message via current transport...
            MimeMessage mimeMessage = mimeMessages[i];
            try {
                if (mimeMessage.getSentDate() == null) {
                    mimeMessage.setSentDate(new Date());
                }
                String messageId = mimeMessage.getMessageID();
                mimeMessage.saveChanges();
                if (messageId != null) {
                    // Preserve explicitly specified message id...
                    mimeMessage.setHeader(HEADER_MESSAGE_ID, messageId);
                }
                Address[] addresses = mimeMessage.getAllRecipients();
                transport.sendMessage(mimeMessage, (addresses != null ? addresses : new Address[0]));
            } catch (Exception ex) {
                Object original = (originalMessages != null ? originalMessages[i] : mimeMessage);
                failedMessages.put(original, ex);
            }
        }
    } finally {
        try {
            if (transport != null) {
                transport.close();
            }
        } catch (Exception ex) {
            if (!failedMessages.isEmpty()) {
                throw new MailSendException("Failed to close server connection after message failures", ex, failedMessages);
            } else {
                throw new MailSendException("Failed to close server connection after message sending", ex);
            }
        }
    }
    if (!failedMessages.isEmpty()) {
        throw new MailSendException(failedMessages);
    }
}
Also used : MailAuthenticationException(org.springframework.mail.MailAuthenticationException) MailSendException(org.springframework.mail.MailSendException) Address(jakarta.mail.Address) AuthenticationFailedException(jakarta.mail.AuthenticationFailedException) MailParseException(org.springframework.mail.MailParseException) NoSuchProviderException(jakarta.mail.NoSuchProviderException) MailAuthenticationException(org.springframework.mail.MailAuthenticationException) MessagingException(jakarta.mail.MessagingException) MailSendException(org.springframework.mail.MailSendException) MailPreparationException(org.springframework.mail.MailPreparationException) MailException(org.springframework.mail.MailException) AuthenticationFailedException(jakarta.mail.AuthenticationFailedException) Date(java.util.Date) LinkedHashMap(java.util.LinkedHashMap) MimeMessage(jakarta.mail.internet.MimeMessage) Transport(jakarta.mail.Transport)

Example 10 with MimeMessage

use of jakarta.mail.internet.MimeMessage in project spring-framework by spring-projects.

the class JavaMailSenderImpl method send.

@Override
public void send(SimpleMailMessage... simpleMessages) throws MailException {
    List<MimeMessage> mimeMessages = new ArrayList<>(simpleMessages.length);
    for (SimpleMailMessage simpleMessage : simpleMessages) {
        MimeMailMessage message = new MimeMailMessage(createMimeMessage());
        simpleMessage.copyTo(message);
        mimeMessages.add(message.getMimeMessage());
    }
    doSend(mimeMessages.toArray(new MimeMessage[0]), simpleMessages);
}
Also used : SimpleMailMessage(org.springframework.mail.SimpleMailMessage) MimeMessage(jakarta.mail.internet.MimeMessage) ArrayList(java.util.ArrayList)

Aggregations

MimeMessage (jakarta.mail.internet.MimeMessage)14 InternetAddress (jakarta.mail.internet.InternetAddress)10 Test (org.junit.jupiter.api.Test)8 MessagingException (jakarta.mail.MessagingException)5 Address (jakarta.mail.Address)4 Session (jakarta.mail.Session)4 Date (java.util.Date)4 Properties (java.util.Properties)4 MailSendException (org.springframework.mail.MailSendException)4 SimpleMailMessage (org.springframework.mail.SimpleMailMessage)4 NoSuchProviderException (jakarta.mail.NoSuchProviderException)3 Transport (jakarta.mail.Transport)3 ArrayList (java.util.ArrayList)3 GregorianCalendar (java.util.GregorianCalendar)3 MailParseException (org.springframework.mail.MailParseException)3 AuthenticationFailedException (jakarta.mail.AuthenticationFailedException)2 MailAuthenticationException (org.springframework.mail.MailAuthenticationException)2 MailException (org.springframework.mail.MailException)2 MailPreparationException (org.springframework.mail.MailPreparationException)2 FileTypeMap (jakarta.activation.FileTypeMap)1