Chris O'Brien
Chris O'Brien

Reputation: 372

Spring JavaMailSender - Change Password?

I have a JavaMailSender bean implemented in Spring. My beans looks as so:

<bean id="mailSender"
        class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="smtp.gmail.com"></property>
        <property name="port" value="587"></property>
        <property name="username" value=""></property>
        <property name="password" value=""></property>
        <property name="javaMailProperties">
        <props>
            <prop key="mail.smtp.auth">true</prop>
            <prop key="mail.smtp.starttls.enable">true</prop>
            <prop key="mail.smtp.ssl.trust">smtp.gmail.com</prop>
        </props>
        </property>
    </bean>
</beans>

It all works fine, so there's no issue. Someone brought up an interesting point. What if someone logs into Gmail and changes the password? Is there a way of editing the password from a web interface, or of setting the value from a database?

Upvotes: 0

Views: 1931

Answers (1)

Dhanush Gopinath
Dhanush Gopinath

Reputation: 5739

What you can do is load the username and properties from a properties file and initialize the bean with properties from that file? So when the password is changed you change the properties file and not the bean definition.

Here is the sample code :

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>
                classpath:mail.properties
            </value>
        </list>
    </property>
</bean>

Your mail.properties file

username=abc
password=abc

Your bean definition

<bean id="mailSender"
        class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="smtp.gmail.com"></property>
        <property name="port" value="587"></property>
        <property name="username" value="${username}"></property>
        <property name="password" value="${password}"></property>
        <property name="javaMailProperties">
        <props>
            <prop key="mail.smtp.auth">true</prop>
            <prop key="mail.smtp.starttls.enable">true</prop>
            <prop key="mail.smtp.ssl.trust">smtp.gmail.com</prop>
        </props>
        </property>
    </bean>
</beans>

If you are looking at storing the password in a database and editing from a web application, then you will have to build that web application and then make the JavaMailSenderImpl use the username/password values fetched from the database at runtime.

Upvotes: 1

Related Questions