开发者

Help when SMTP server hangs when sending emails from Java

I use an external mail server to send SMTP mails, this server is effectively beyond my control.

A couple of times recently this mail server has had issues and it's caused my Java (Struts/Spring) app to completely hang when wa开发者_如何学运维iting for a reply from the mail server.

I'm using the Spring org.springframework.mail.javamail.JavaMailSender to send mails.

When the external mail server is having issues it's the following line that freezes mailEngine.send(mailMessage);

I don't mind that sometimes emails don't get sent but how can I stop this from freezing my application while it waits for a reply from the SMTP server?

Are there any good email queuing solutions for Java?


You can send the emails in a background thread.


Thread your calls to the SMTP server. You can make use of the ExecutorService (various implementations exist) and drop in Runnables to be executed at a later stage (out of band). The advantage of this approach is that you don't have to explicitly code your threading model.

If you collect the Future object from the Executor upon submission, you can call get() with a suitable timeout and cancel (and perhaps re-submit/retry) upon timeout.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜