Parker Smith Software

 

Using GMail to send email from Rails

By Brian Webb

18 Aug 2008

Sometimes when we are making applications that send email we need to send them from our development machines, I'm not a fan of installing postfix or other MTA (mail transfer agent) software on everyone's computer, and that also adds another level of complexity for cross platform development. Instead we'd rather have everything all integrated into our rails application so that it just works for development, then leave the setup of postfix or another MTA to the deployment process. We do this by setting up the rails application to send email through GMail or Google Apps in development mode, and the server MTA in production mode.

One side note, it probably isn't a good idea to send email this way in production mode since your app can stall while the email is being sent, and an MTA will have a mail queue to handle that.

To work with GMail we have to connect to SMTP through SSL, to do this we need to install the 'tlsmail' gem.

1
2

sudo gem install tlsmail
Next create an initializer in config/initializers:
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

# config/initializers/email_config.rb

if ENV['RAILS_ENV'] == "production"
  
  ActionMailer::Base.delivery_method = :smtp
  ActionMailer::Base.smtp_settings = {
    :address => '127.0.0.1',
    :port => 25,
    :domain => 'localhost'
  }

else

  #setup tlsmail so we can send email through SSLed SMTP
  require 'tlsmail'
  Net::SMTP.enable_tls(OpenSSL::SSL::VERIFY_NONE)

  ActionMailer::Base.delivery_method = :smtp
  ActionMailer::Base.smtp_settings = {
    :address => 'smtp.gmail.com',
    :port => 587,
    :domain => 'yourdomain.com',
    :authentication => :plain,
    :user_name => 'maileraccount@yourdomain.com',
    :password => 'yourpassword'
  }
  
end #end if

If you are using a Google Apps account then just replace the domain and username info with your own, if you are just using a gmail account the domain is gmail.com and the username is just your GMail id without the @gmail.com.

One thing to note, Google has limits on outgoing emails of about 100 per day per account to prevent people from using their service to send out spam.

 
 
 
No Spam: 4 + 2 =
 
August 18, 2008 - Brian Webb
0