Using Swoosh and Oban for Email Delivery in Elixir Applications

199
clicks
Using Swoosh and Oban for Email Delivery in Elixir Applications
Peter Ullrich's article focuses on a common feature required in most applications: email sending. He explains the drawbacks of sending emails synchronously as part of user actions like purchases, such as potential service unavailability or bugs causing critical failures. The alternative, asynchronous email sending, is shown to be more reliable, enabling the app to function even if the email service is down, though with the risk of emails being lost in case of abrupt server shutdowns. To address this, Ullrich suggests utilizing Oban, a robust background processing library, to queue and manage email sending tasks, thereby combining the benefits of both methods. Ullrich then provides a code walkthrough for converting an existing Phoenix app to use Oban workers for email delivery. He refactors the auto-generated 'UserNotifier' module, replacing direct mail delivery with an email job being enqueued to Oban. However, a challenge with Oban is its need to serialize job arguments as JSON, which doesn't support Elixir's tuple structures found in 'Swoosh.Email' structs. To solve this, Ullrich introduces helper functions for converting between 'Swoosh.Email' structs and simple maps, ensuring compatibility with Oban's serialization requirements. The article concludes with the final piece of the puzzle: the Oban worker module responsible for the actual email sending. This module is designed to fail in case of an email delivery error, allowing Oban to handle retries and providing a robust, failure-tolerant email system. Ullrich's experience as a Senior Elixir developer provides a pragmatic approach to handling emails and demonstrates leveraging Elixir's concurrency tools to build resilient systems.

© HashMerge 2024