Monday, March 14, 2011

Send Secure Email Via Gmail in Ruby 1.8.7

NoteThis post was originally posted on my old blog on 8th of June 2010
I'm working on a small web app in my spare time in which I need to send out emails with attachments in Ruby on Rails... First step is to actually send an email... I wanted to do this using my Gmail account so that any responses that might come back would be into my everyday email account. I also wanted it to use SSL/TLS... This whole thing was a bit difficult to figure out especially with the smtp_tls.rb examples on the net. I got a bit confused...
For Ruby 1.8.6 (and maybe older) see here

This is the code that I have come up with for Ruby 1.8.7 in the end...
require 'net/smtp'

smtp = Net::SMTP.new 'smtp.gmail.com', 587
smtp.enable_starttls

message = <<EMAIL_MESSAGE
From: John Smith <example_from@gmail.com>
To: Joe Smith <example_to@gmail.com>
Subject: Just a little test...
This is test...
EMAIL_MESSAGE

smtp.start('smtp.gmail.com',
           'gmail_username_here','password_here', :plain ) do |smpt|
    smtp.send_message message,
        'example_from@gmail.com',
        'example_to@gmail.com'
end
Some notes:
  • In Ruby 1.8.7 you don't have to install the smtp_tls gem like you did in prior versions as this is included in the net/smtp.rb file already. you just have to set smtp.enable_starttls before you call start(..)
  • You don't have to put the @gmail.com part on the end of you email in the gmail_username_here place hold.
  • The body of the message has to be constructed fully, you can't call functions to build it... There are a couple of other gems that you can use to make this a little nicer. Some things to look at include : mail, TMail for example, which may make this a bit cleaner.
The rest should be fairly straight forward. The next piece in the puzzle with be figuring out how to add attachments and then figuring out how to render a PDF in prawnto as an attachment, in rails; without saving it as a file first :)

No comments:

Post a Comment