- Date
Attach files to your email in Elixir using Swoosh
The Swoosh team just released a new version of Swoosh that includes support for attachments. It works out of the box with all built-in adapters.
Intro to Swoosh
If you know what Swoosh is already you can jump to the next part.
Swoosh is an Elixir library for easily composing, delivering and testing emails in your projects.
It has built-in adapters for a lot of the transactional email providers out there, including:
Additionally it has a SMTP adapter which means it can virtually works with any email provider and SMTP server.
You can also hook into the Phoenix rendering engine thanks to this extension, making the integration with your web projects even easier.
Read our “Getting Started” guide to start using Swoosh in your project now.
Or if you want to learn more, head to the documentation.
Attaching files to your email
Once you have Swoosh setup, adding attachments to your email is as simple as using the Swoosh.Email.attachment/2
function and giving it a path to a file:
import Swoosh.Email
new()
|> to("peter@example.com")
|> from({"Jarvis", "jarvis@example.com"})
|> subject("Invoice May")
|> text_body("Here is the invoice for your superhero services in May.")
|> attachment("/Users/jarvis/invoice-peter-may.pdf")
You can also pass it a %Plug.Upload{}
struct. In this example we have manually crafted the upload struct but in the real world you would probably get it as one of the params of your request after a successful upload.
import Swoosh.Email
upload_invoice = %Plug.Upload{
path: "/tmp/plug/DEFfF014AaA01F",
content_type: "",
filename: "invoice-peter-may.pdf"
}
new()
|> to("peter@example.com")
|> from({"Jarvis", "jarvis@example.com"})
|> subject("Invoice May")
|> text_body("Here is the invoice for your superhero services in May.")
|> attachment(uploaded_invoice)
Of course, you can have multiple attachments, just use the attachment/2
function multiple times!
Note that we don’t support inline attachments yet but it’s on the roadmap and you shouldn’t have to wait too long before it’s the case. See https://github.com/swoosh/swoosh/issues/122.
Please feel free to report any issues that you run into while working with this new release.