Email - Setting parameters for mail account at runtime

We are setting the parameters for EMail account at design time through application.properties file as below;

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.protocol=smtp
spring.mail.username=**********@*****.com
spring.mail.password=************
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

Can the user set these parameter at runtime as user may not be willing to share these parameters with developer. We have also searched JMX console for “mail” keyword, no mail parameters appear. Please guide.

Hi @vimleshjaipur,

Spring Bean sending emails using the provided configuration in application.properties is created as a singleton bean on the application startup. There is no ability to change these properties at runtime. If you would like to use external values for Spring Boot application properties, you can set them as environment variables and use these values in application.properties. For example,

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.protocol=smtp
spring.mail.username=${SPRING_MAIL_USERNAME}
spring.mail.password=${SPRING_MAIL_PASSWORD}
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

where, SPRING_MAIL_USERNAME, SPRING_MAIL_PASSWORD - environment variables containing required values.

You can find more information about externalized configuration for Spring Boot application here.

Regards,
Maria.

Thanks for the reply.
The option of externalized configuration does not appears easy one. In JMX console, there is a MBean jmix.email several attributes are available but on right click, the change value link is disabled and there is no password attribute. Is there any possibility, from here the admin may change these attributes. Thanks

@vimleshjaipur It is not possible to change application properties from JMX console.

If you would like to change email properties in the runtime using UI and apply them during email sending, it is required to add a custom implementation:

  1. Store properties in the database and load values from it when sending an email. Here you can use the Application Settings add-on. This add-on gives an ability to change properties from the UI.
  2. Create Spring Bean that extends org.springframework.mail.javamail.JavaMailSenderImpl and overrides methods which should return settings stored in the database. In your case, username and password. Note: if you would like to use other properties from Spring Boot Mail configuration (properties starting with spring.mail) in your bean, need to manually set it.
  3. Mark bean from the previous step as primary.

This project runtime-email-props.zip (115.5 KB) сontains an example implementation of the steps described above.

Regards,
Maria.

1 Like

Thanks Maria.