Search in sources :

Example 1 with Transport

use of jakarta.mail.Transport in project gocd by gocd.

the class GoSmtpMailSender method send.

@Override
public ValidationBean send(String subject, String body, String to) {
    Transport transport = null;
    try {
        LOGGER.debug("Sending email [{}] to [{}]", subject, to);
        Properties props = mailProperties();
        MailSession session = MailSession.getInstance().createWith(props, mailHost.getUsername(), mailHost.getPassword());
        transport = session.getTransport();
        transport.connect(mailHost.getHostName(), mailHost.getPort(), StringUtils.trimToNull(mailHost.getUsername()), StringUtils.trimToNull(mailHost.getPassword()));
        MimeMessage msg = session.createMessage(mailHost.getFrom(), to, subject, body);
        transport.sendMessage(msg, msg.getRecipients(TO));
        return ValidationBean.valid();
    } catch (Exception e) {
        LOGGER.error("Sending failed for email [{}] to [{}]", subject, to, e);
        return ValidationBean.notValid(ERROR_MESSAGE);
    } finally {
        if (transport != null) {
            try {
                transport.close();
            } catch (MessagingException e) {
                LOGGER.error("Failed to close transport", e);
            }
        }
    }
}
Also used : MimeMessage(jakarta.mail.internet.MimeMessage) MessagingException(jakarta.mail.MessagingException) Transport(jakarta.mail.Transport) Properties(java.util.Properties) MessagingException(jakarta.mail.MessagingException)

Example 2 with Transport

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

the class JavaMailSenderImpl method connectTransport.

/**
 * Obtain and connect a Transport from the underlying JavaMail Session,
 * passing in the specified host, port, username, and password.
 * @return the connected Transport object
 * @throws MessagingException if the connect attempt failed
 * @since 4.1.2
 * @see #getTransport
 * @see #getHost()
 * @see #getPort()
 * @see #getUsername()
 * @see #getPassword()
 */
protected Transport connectTransport() throws MessagingException {
    String username = getUsername();
    String password = getPassword();
    if ("".equals(username)) {
        // probably from a placeholder
        username = null;
        if ("".equals(password)) {
            // in conjunction with "" username, this means no password to use
            password = null;
        }
    }
    Transport transport = getTransport(getSession());
    transport.connect(getHost(), getPort(), username, password);
    return transport;
}
Also used : Transport(jakarta.mail.Transport)

Example 3 with Transport

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

Aggregations

Transport (jakarta.mail.Transport)3 MessagingException (jakarta.mail.MessagingException)2 MimeMessage (jakarta.mail.internet.MimeMessage)2 Address (jakarta.mail.Address)1 AuthenticationFailedException (jakarta.mail.AuthenticationFailedException)1 NoSuchProviderException (jakarta.mail.NoSuchProviderException)1 Date (java.util.Date)1 LinkedHashMap (java.util.LinkedHashMap)1 Properties (java.util.Properties)1 MailAuthenticationException (org.springframework.mail.MailAuthenticationException)1 MailException (org.springframework.mail.MailException)1 MailParseException (org.springframework.mail.MailParseException)1 MailPreparationException (org.springframework.mail.MailPreparationException)1 MailSendException (org.springframework.mail.MailSendException)1