Mailers
Start sending and receiving emails from and to your Crystal application
Azu leverages the Carbon library for writing, sending, and testing emails. Carbon can be configured using the default file generated with a new Azu application in initializers/carbon.cr
. In that file, you can add SendGrid keys and change adapters.
Installation
Add this to your application's shard.yml
:
Adapters
Carbon::SendGridAdapter
- See luckyframework/carbon_sendgrid_adapter.Carbon::SmtpAdapter
- See luckyframework/carbon_smtp_adapter.Carbon::AwsSesAdapter
- See keizo3/carbon_aws_ses_adapter.Carbon::SendInBlueAdapter
- See atnos/carbon_send_in_blue_adapter.Carbon::MailgunAdapter
- See atnos/carbon_mailgun_adapter.Carbon::SparkPostAdapter
- See Swiss-Crystal/carbon_sparkpost_adapter.Carbon::PostmarkAdapter
- See makisu/carbon_postmark_adapter.Carbon::MailersendAdapter
- See balakhorvathnorbert/carbon_mailersend_adapter.
Usage
First, create a base class for your emails
Configure the mailer class
Create a class for your email
Create templates
Templates go in the same folder the email is in:
Text email:
<folder_email_class_is_in>/templates/<underscored_class_name>/text.ecr
HTML email:
<folder_email_class_is_in>/templates/<underscored_class_name>/html.ecr
So if your email class is in src/emails/welcome_email.cr
, then your templates would go in src/emails/templates/welcome_email/text|html.ecr
.
For more information on what you can do with Embedded Crystal (ECR), see the official Crystal documentation.
Template layouts
Layouts are optional allowing you to specify how each email template looks individually. If you'd like to have the same layout on each, you can create a layout template in <folder_email_class_is_in>/templates/<layout_name>/layout.ecr
In this file, you'll yield the main email body with <%= content %>
. Then in your BaseEmail
, you can specify the name of the layout.
Deliver the email
Delay email delivery
The built-in delay uses the deliver_later_strategy
setting set to Carbon::SpawnStrategy
. You can create your own custom delayed strategy that inherits from Carbon::DeliverLaterStrategy
and defines a run
method that takes a Carbon::Email
and a block.
One example might be a job processor:
Testing
Change the adapter
Reset emails before each spec and include expectations
Integration testing
Unit testing
Unit testing is simple. Instantiate your email and test the fields you care about.
Note that unit testing can be superfluous in most cases. Instead, try unit testing just fields that have complex logic. The compiler will catch most other issues.
Last updated