mark cerqueira well-rounded nerd

Authenticating Programmatically Sent Emails

Work on the Ruby and Sinatra project continues and this weekend I worked on creating a helper method for sending emails so I can have users confirm the emails they used to register. I wanted to send emails from a mailbox I set up on a custom domain I’m hosting with DreamHost. I created a mailbox on DreamHost’s admin panel and with the mail Ruby gem it was pretty straightforward to get emails sent.

 
class ApplicationController < Sinatra::Base

  # Configure mail gem
  # You can use the config_env gem to save sensitive information (https://github.com/SergXIIIth/config_env)
  options = { :address              => 'www.yourdomain.com',
              :port                 => 587,
              :user_name            => 'welcome@yourdomain.com',
              :password             => 'yourpassword',
              :authentication       => 'plain',
              :enable_starttls_auto => true,
              :openssl_verify_mode  => OpenSSL::SSL::VERIFY_NONE }
  
  Mail.defaults do
    delivery_method :smtp, options
  end
	
  get '/mailtest/?' do
    Mail.deliver do
      to user@yourdomain.com
      from 'Welcome <welcome@yourdomain.com'
      subject 'Test Subject'
      body 'Test Body'
    end
  end
end

Hit and the endpoint and you’re done! Or are you? To the Gmail inbox!

Gmail has some doubts!

All looks good except Gmail ominously warns us: “Gmail couldn’t verify that chuckpad.io actually sent this message.” This means “Gmail doesn’t know if the message is coming from the person who appears to be sending it,” which makes our messages excellent candidates to get caught by Gmail’s spam filters! Read more about authenticated messages here.

After some digging around, I learned about Sender Policy Framework (SPF) records. Basically, a DNS record can have some metadata which identifies which servers are permitted to send email on behalf of the domain. DreamHost’s default “SPF information doesn’t include DreamHost’s mail servers” because you can always opt to host your domain’s mail servers elsewhere. Fortunately, this can be easily remedied by adding the SPF record v=spf1 include:netblocks.dreamhost.com to our domain’s DNS record.

Gmail's doubts are gone!

Give the DNS caches of the world a few hours to refresh, try again, and boom! Success! Programmatic and authenticated!