There are multiple ways to achieve this functionality.
Synchronous Call
This is the one which you are already using. Code (synchronously) invokes Java Mail API and waits for API to complete the execution. The process may take time depending on the complexity of building the email message (fetching records from Database, reading images/documents (attachments), communication with Mail Server etc.
Trade-offs
- For individual requests(web/desktop), response latency will increase based on the time it takes to construct and send email.
- An exception in sending email, may require redo of entire process (if retried).
- Transactional data (e.g. DB) may be rolled back, due to exception while sending email. This may not be desired behavior.
- Overall application latency will increase, if similar functionality is invoked by multiple users concurrently.
- Email retry functionality may not be possible, if email sending code is tightly coupled with other functional code.
Multithreading Approach
Create a separate thread to asynchronously send an email. Calling code need not have to wait for Email send functionality to complete and execute rest of the code. Ideally, should make use of ThreadPool, instead of blandly creating new threads.
Trade-offs
Though, request latency will go down, it is still not reliable. Any exception occurred while constructing/sending email may result into, no email sent to user.
Email sending functionality can't be distributed across multiple machines.
Retry functionality is possible, since email code is separated into separate class. This class can be independently called, without a need of redoing other things.
Asynchronous Processing
Create a class, which accepts Email request and stores it in either database or messaging infrastructure (e.g. JMS). The message listeners will process the task as and when it arrives and update the status against each task.
Trade-offs
- Email requests can be processed in distributed mode.
- Retry email possible, without having any side effects.
- Complex implementation as multiple components are involved in processing, persisting email requests.