Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Javamail properties from Database

I'm trying to write a Spring(I use 3.0) Application and use the Spring included Javamail. I would like the javamail properties (stmp server, port, username, pass,etc) to be stored in a database for easy updating/changing. I've seen examples where Javamail properties are setup inside the applicationContext.xml or in a properties file.

but is there a way to use a database to store the email properties and retrieve them every time I need to send a e-mail?

my ApplicationContex.xml

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="defaultEncoding" value="UTF-8" />
    <property name="host" value="smtp.gmail.com" />
    <property name="port" value="465" />
    <property name="protocol" value="smtps" />
    <property name="username" value="[email protected]" />
    <property name="password" value="***********" />
    <property name="javaMailProperties">
        <props>
            <prop key="mail.smtps.auth">true</prop>
            <prop key="mail.smtps.starttls.enable">true</prop>
            <prop key="mail.smtps.debug">true</prop>
        </props>
    </property>
</bean>

Thanks for any help.

like image 890
Joe Avatar asked Nov 18 '25 22:11

Joe


1 Answers

Sure, you can.

1) First way

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"/>

In controller

@Autowired 
JavaMailSender mailSender


@PostConstruct
public void init(){
    // connect to database
    // obtain properties
    JavaMailSenderImpl ms = (JavaMailSenderImpl) mailSender;
    ms.set...
    ms.set...
    ms.set...
}

2) Second way

public class DatabaseBasedMailSender extends JavaMailSenderImpl{

    public DatabaseBasedMailSender(){
        // connect to database
        // obtain properties

        setHost(...)
        setProtocol(...)
        ...

    }


}

<bean id="mailSender" class="my.project.DatabaseBasedMailSender"/>

I am sure it is possible find another ways to do this.

like image 108
Georgy Gobozov Avatar answered Nov 20 '25 13:11

Georgy Gobozov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!