We use Mailgun to send emails from our apps.
-
Check Last Pass if the client already has a Mailgun account.
-
Create an account if they don't. The email template is: mailgun+{client}@infinum.hr
-
Create a domain for the app.
-
Contact your friendly neighborhood DevOps to add DNS records for domain verification.
-
Add the
mailgun_rails
gem to the gemfile. -
Add smtp settings to your app. Example:
config.action_mailer.delivery_method = :mailgun config.action_mailer.mailgun_settings = { api_key: Rails.application.secrets.mailgun[:api_key], domain: Rails.application.secrets.mailgun[:domain] }
-
Profit
The HTTP API has some advantages over SMTP:
- It’s faster.
- It's better for large-scale sending.
- You don’t have to deal with MIME because Mailgun will assemble it on their side.
- Request libraries are available for your language of choice.
If you want to track your emails for more than 7 days (which is the retainer period for free Mailgun), you need to setup webhooks to our email aggregation service.
When the staging and production databases are in sync, the users and their emails are also in sync. Sometimes, we trigger an action which could send emails to real users. To prevent this, we should intercept all emails that are sent to real users from the staging environment.
We use recipient_interceptor to restrict emails at staging.
-
Add the
recipient_interceptor
gem to the gemfile -
Add the gem settings in config/environments/staging.rb. Example:
Mail.register_interceptor( RecipientInterceptor .new(Rails.application.secrets.permitted_emails, subject_prefix: '[STAGING]') )
-
Add the permitted_emails key in secrets.yml under the staging section.
-
If you want to set more then one email address, they should be separated with a comma (e.g., '[email protected],[email protected]').
If everything is configured well, all emails will be delivered to the specified email addresses.
Preview an email in the default browser instead of sending it. This is great for two reasons:
- You don't need to set up email delivery in the development environment.
- There is no risk of accidentally sending a test email to a real user when developing and testing.
We use letter_opener to preview emails in development.
-
Add the
letter_opener
gem to the gemfile (in the development group) -
Set the delivery method in config/environments/development.rb. Example:
config.action_mailer.delivery_method = :letter_opener
Rails also has a built-in feature for previewing emails. Using it allows you to see what the email looks like without sending a real email.