javaspring-boot.env

SpringBoot won't read mail properties from .env.properties file


I'm using a .env.properties file for sensitive data such as Database and Mail credentials. The database credentials are being picked up by Spring properly, but the mail credentials are not. Here is an example of how my .env.properties and application.properties files look like. Keep in mind, the app works if I provide the mail details in the application.properties directly.

.env.properties:

DB_HOST=jdbc:mysql://localhost:3306/randomDbName
DB_USER=root
DB_PASSWORD=root

MAIL_HOST=sandbox.smtp.mailtrap.io
MAIL_PORT=25
MAIL_USER=randomUser
MAIL_PASSWORD=randomPassword
MAIL_PROTOCOL=smtp

application.properties:

# Read configs from .env
spring.config.import=file:.env.properties

### Mail Properties ###
spring.mail.host=${MAIL_HOST}
spring.mail.port=${MAIL_PORT}
spring.mail.username=${MAIL_USER}
spring.mail.password=${MAIL_PASSWORD}
spring.mail.protocol=${MAIL_PROTOCOL}

### Database Properties ###
spring.datasource.url=${DB_HOST}
spring.datasource.username=${DB_USER}
spring.datasource.password=${DB_PASSWORD}
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

### Jwt Properties ###
jwt.expiration.time=3600000

This is the error I get: Could not resolve placeholder 'MAIL_HOST' in value "${MAIL_HOST}" But it resolves the Database credentials, I don't see why these are different.

Also I use the JavaMailSender in my MailServiceImpl like this:

@Service
public class MailServiceImpl implements MailService {

    private final JavaMailSender javaMailSender;

    public MailServiceImpl(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    @Override
    public void send(Notification notification) {

        MimeMessagePreparator mimeMessagePreparator = mimeMessage -> {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
            messageHelper.setFrom("email@domain.com");
            messageHelper.setTo(notification.getRecipient());
            messageHelper.setSubject(notification.getSubject());
            messageHelper.setText(notification.getContent());
        };

        javaMailSender.send(mimeMessagePreparator);
    }
}

Also, I have the necessary dependency:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

Solution

  • use complete path from project root:

    spring.config.import=file:./src/main/resources/.env.properties