I'm developing an application with Spring. This application has customers, and each customer has his own mail server configuration (port, host, username, password,etc). My application must send emails through the Customers mail servers. I mean, I cannot use the classic:
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
There are going to be many MailServerImpls, one per customer, and I will have hundreds of them. Each time a Customer signs in, he is asked for this mail server configuration.
Upon certain actions of the customer, my application must send an email using the Customer mail server.
So, what is the best way to do this with Spring?
I hope the best solution is not to do a
new MailServerImpl() and set the attributes each time I have to send an email...
Thank you very much.Answer1:
Read the port, host, username, password,etc from a .properties file or from the database. This way you will have one mailSender implementation but configured different per client.
You could use <a href="http://commons.apache.org/proper/commons-email/userguide.html" rel="nofollow">Apache Commons Email</a> and not using a bean but creating an object everytime and sending the mail:
Email email = new SimpleEmail(); email.setHostName("smtp.googlemail.com"); email.setSmtpPort(465); email.setAuthenticator(new DefaultAuthenticator("username", "password")); email.setSSLOnConnect(true); email.setFrom("email@example.com"); email.setSubject("TestMail"); email.setMsg("This is a test mail ... :-)"); email.addTo("firstname.lastname@example.org"); email.send();
The values you would store in the database in a relationship to the user.Answer2:
This question is a bit vague to me, without going into details how you represent customer and their email server configuration.
What you could do is to have mapping between Customers and their configuration in some dictionary structure.
Accept concurrent requests from customer(with their identifier) and add it to some FIFO queue, then have a thread pool accepting and processing these requests as they come. You would have control on number of worker threads and Email implementation instances which could be reused.
Each thread could be associated with instance of whichever Email implementation you are using if this implementation has class variables. You could maybe use Email abstraction singleton shared between all threads, where connection properties are only in local scope of method.