It’s incredible how easy it is to send emails through a web application, there’s no wonder we get so much spam. Assuming we have a ruby app using Sinatra, Pony is one of the easiest ways to get started with your own spam empire.
Installation is, as always, trivial with ruby. Install the gem with gem install pony
or add gem pony
to your Gemfile
and run bundle install
.
I like to configure Pony in my application’s configure
block. I could also add it to my config.ru
, but I like to keep that file as tiny as posible to avoid having configuration code all over the place.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
This block tells Pony to use the SendGrid server to send mail, use the “myapp.com” HELO domain, and dig up the username and password fields from my environment.
If you’re using Heroku to host your application, you can sign up for a SendGrid account through your Heroku app, which gives you instant access to your SendGrid account. The username
and password
field you need to fill in your environment are automatically populated in your Heroku config, which you can view by running heroku config
for your application. The free account gets you up to 200 emails a day.
Since I might have multiple developers working in my source code and testing the email-sending functionality, I have all the developers sign up for their own free SendGrid account. This should help to alleviate some of the email volume from any particular account while developing. After signing up, it took my account nearly 4 hours to be “provisioned” (see: approved) by the SendGrid team. Once you’re approved you can start sending emails using your developer account credentials. I stick my username/password in my local .env
file (another reason to make sure you’re not storing your environment on your server or in your git repo).
So let’s actually send an email. Let’s create a route that sends an email to verify a new user account; I’ll take some liberties by saying we have a User
model defined already that generates a signup verification hash. I can tell pony to send a plaintext body through the body
option and an HTML body through the html_body
option.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
|
When you have a user hit this route, an email will be sent to the user with the given subject, to, from, and body fields using the configuration parameters given in the previous configure
block. Fast, easy, and, best of all, no sendmail
configuration.