Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple mail servers on a Spring application

Tags:

java

email

spring

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.

like image 791
oscar serrano Avatar asked Mar 23 '15 21:03

oscar serrano


2 Answers

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 Apache Commons Email 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 protected]");
email.setSubject("TestMail");
email.setMsg("This is a test mail ... :-)");
email.addTo("[email protected]");
email.send();

The values you would store in the database in a relationship to the user.

like image 170
Robert Niestroj Avatar answered Sep 27 '22 17:09

Robert Niestroj


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.

like image 45
John Avatar answered Sep 27 '22 16:09

John