Skip to content

Allow verification of mail credentials on startup #49360

@odrotbohm

Description

@odrotbohm

With a standard spring-boot-starter-mail setup and mail server properties configured, one ends up with a MailSender bean in the context that's usually used to send email at some point in the application lifecycle. That said, the credentials are not verified until the first email was sent.

One can register an ApplicationRunner to perform the verification on startup like this:

import jakarta.mail.MessagingException;

import java.util.Optional;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;

@Component
@ConditionalOnBean({JavaMailSenderImpl.class, MailProperties.class})
class MailCredentialsVerifier implements ApplicationRunner {

	private final JavaMailSenderImpl mailSender;
	private final MailProperties properties;

	// Constructor and log omitted

	@Override
	public void run(ApplicationArguments args) throws Exception {

		var host = properties.getHost();
		var user = properties.getUsername();

		try {
			mailSender.get().testConnection();
			log.info("Successfully verified mail credentials for {} on {}.", user, host);
		} catch (MessagingException e) {
			log.error("Unable to verify mail credentials for {} on {}.", user, host);
			throw new IllegalStateException("Invalid mail credentials orunreachable mail server: " + e.getMessage(), e);
		}
	}
}

It would be nice if some mechanism like this was available out of the box, maybe behind an opt-in or -out property.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions