Hüseyin BABAL
Hüseyin BABAL

Reputation: 15550

Spring mvc send mail as non-blocking

I am developing an application and that application sends mail in some cases. For example;

When user updates his email, an activation mail sent to user in order to validate new email address. Here is a piece of code;

............
if (!user.getEmail().equals(email)) {
            user.setEmailTemp(email);
            Map map = new HashMap();
            map.put("name", user.getName() + " " + user.getSurname());
            map.put("url", "http://activationLink");
            mailService.sendMail(map, "email-activation");
        }
return view;

My problem is response time gets longer because of email sending. Is there any way to send email like non-blocking way? For example, Mail sending executes at background and code running continues

Thanks in advance

Upvotes: 7

Views: 3469

Answers (2)

Tran Tuyen
Tran Tuyen

Reputation: 29

Same as above.

But remember to enable Async task in Spring configuration file (Ex: applicationContext.xml):

<!-- Enable asynchronous task -->
<task:executor id="commonExecutor" pool-size="10"  />
<task:annotation-driven executor="commonExecutor"/>

Or configuration class:

@Configuration
@EnableAsync
public class AppConfig {
}

Upvotes: 1

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280102

You can setup an asynchronous method with Spring to run in a separate thread.

@Service
public class EmailAsyncService {
    ...
    @Autowired
    private MailService mailService;

    @Async
    public void sendEmail(User user, String email) {
        if (!user.getEmail().equals(email)) {
            user.setEmailTemp(email);
            Map map = new HashMap();
            map.put("name", user.getName() + " " + user.getSurname());
            map.put("url", "http://activationLink");
            mailService.sendMail(map, "email-activation");
        }
    }
}

I've made assumptions here on your model, but let's say you could pass all the arguments needed for the method to send your mail. If you set it up correctly, this bean will be created as a proxy and calling the @Async annotated method will execute it in a different thread.

 @Autowired
 private EmailAsyncService asyncService;

 ... // ex: in controller
 asyncService.sendEmail(user, email); // the code in this method will be executed in a separate thread (you're calling it on a proxy)
 return view; // returns right away

The Spring doc should be enough to help you set it up.

Upvotes: 7

Related Questions