has_emails demonstrates a reference implementation for sending emails with logging and asynchronous support.
Emailing between users and other parts of a system is a fairly common feature in web applications, especially for those that support social networking. Emailing doesn't necessarily need to be between users, but can also act as a way for the web application to send notices and other notifications to users.
Rails already provides ActionMailer as a way of sending emails. However, the framework does not provide an easy way to persist emails, track their status, and process them asynchronously. Designing and building a framework that supports this can be complex and takes away from the business focus. This plugin can help ease that process by demonstrating a reference implementation of these features.
has_emails requires an additional database table to work. You can generate a migration for this tables like so:
Then simply migrate your database:
Creating new emails
Emails should usually still be created using ActionMailer. However, instead of delivering the emails, you can queue the emails like so:
Notifier.deliver_signup_notification(david) # sends the email now Notifier.queue_signup_notification(david) # sends the email later (has_emails kicks in)
In addition to queueing emails, you can build them directly like so:
email_address = .find(123) email = email_address.emails.build email.to .find(456) email.subject = 'Hey!' email.body = 'Does anyone want to go out tonight?' email.deliver
Replying to emails
reply = email.reply_to_all reply.body = "I'd love to go out!" reply.deliver
forward = email.forward forward.body = 'Interested?' forward.deliver
Processing email asynchronously
In addition to delivering emails immediately, you can also queue emails so that an external application processes and delivers them (as mentioned above). This is especially useful when you want to asynchronously send e-mails so that it doesn't block the user interface on your web application.
To process queued emails, you need an external cron job that checks and sends them like so:
.with_state('queued').each do |email| email.deliver end
Before you can run any tests, the following gem must be installed:
To run against a specific version of Rails:
rake test RAILS_FRAMEWORK_ROOT=/path/to/rails