Joe
Joe

Reputation: 4542

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.

Upvotes: 2

Views: 7583

Answers (3)

Arijeet Bhakat
Arijeet Bhakat

Reputation: 99

One way of doing it would be to create a singleton bean to initialize all your email related properties :

  1. Obtain all the email related properties from DB and set them as System/Environment Property
  2. Fetch all of those properties as required below with System.getProperty("propertyName")

    @Configuration
    public class EmailConfig {
    
    @Bean
    public JavaMailSender getJavaMailSender() {
    
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost("");
        mailSender.setPort(Integer.valueOf("");
        mailSender.setDefaultEncoding("");
        mailSender.setUsername("");
        mailSender.setPassword("");
    
        Properties props = mailSender.getJavaMailProperties();
        props.put("spring.mail.protocol","");
        props.put("mail.smtps.starttls.enable","");
        props.put("mail.smtp.auth","");
    
        return mailSender;
       }
    }
    

Upvotes: 1

Georgy Gobozov
Georgy Gobozov

Reputation: 13731

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.

Upvotes: 7

Sheel
Sheel

Reputation: 845

You can also make a properties file and from there you can get all the values like host,username,password ,I do'nt think that it is good idea to store in database,but if you want you can use..Any time you want to change in your mail setting ,you can go in properties file and change there,I have created separate util package for sending mail

public void sendMailWithAttachments(String to, String subject,
        String content, String[] attachFiles) {

    try {
        final String userName = com.sheel.property.Properties.userName;
        final String password = com.sheel.property.Properties.password;
        String from = com.sheel.property.Properties.mailFrom;
        Properties props = new Properties();
        props.put("mail.smtp.host",
                com.sheel.property.Properties.SMTP_HOST);
        props.put("mail.smtp.socketFactory.port",
                com.sheel.property.Properties.SMTP_PORT);
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port",
                com.sheel.property.Properties.SMTP_PORT);

        Session session = Session.getInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication 

                    getPasswordAuthentication() {
        return new    PasswordAuthentication(userName,
                                password);
                    }
                });

        Message msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(from));
        msg.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(to));
        msg.setSubject(subject);
        msg.setSentDate(new Date());

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(content, "text/html");

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        if (attachFiles != null && attachFiles.length > 0) {
            for (String filePath : attachFiles) {
                MimeBodyPart attachPart = new MimeBodyPart();

                try {
                    attachPart.attachFile(filePath);
                } catch (IOException ex) {
                    ex.printStackTrace();
                    throw ex;
                }

                multipart.addBodyPart(attachPart);
            }
        }

        msg.setContent(multipart);

        Transport.send(msg);

        System.out.println("Mail sent");
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

And this is properties file

public interface Properties {
String SMTP_HOST = "smtpout.secureserver.net";
String SMTP_PORT = "465";
String incoming_server_host = "pop.secureserver.net";
String incoming_server_port = "995";
String userName = "[email protected]";
String password = "password";
}

Upvotes: 1

Related Questions