43

I am using the mail gem for Ruby https://github.com/mikel/mail

How do I send an email via an smtp server? How do I specify the address and port? And what settings should I use for Gmail?

The README on github only gives examples sending by a local server.

barry
  • 4,037
  • 6
  • 41
  • 68
Colonel Panic
  • 132,665
  • 89
  • 401
  • 465

1 Answers1

99

From http://lindsaar.net/2010/3/15/how_to_use_mail_and_actionmailer_3_with_gmail_smtp

To send out via GMail, you need to configure the Mail::SMTP class to have the correct values, so to try this out, open up IRB and type the following:

require 'mail'

options = { :address              => "smtp.gmail.com",
            :port                 => 587,
            :domain               => 'your.host.name',
            :user_name            => '<username>',
            :password             => '<password>',
            :authentication       => 'plain',
            :enable_starttls_auto => true  }



Mail.defaults do
  delivery_method :smtp, options
end

The last block calls Mail.defaults which allows us to set the global delivery method for all mail objects that get created from now on. Power user tip, you don’t have to use the global method, you can define the delivery_method directly on any individual Mail::Message object and have different delivery agents per email, this is useful if you are building an application that has multiple users with different servers handling their email.

Mail.deliver do
       to 'mikel@test.lindsaar.net'
     from 'ada@test.lindsaar.net'
  subject 'testing sendmail'
     body 'testing sendmail'
end
bonafernando
  • 1,048
  • 12
  • 14
Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
  • 3
    I'm getting the following error: `/usr/local/rvm/rubies/ruby-1.9.3-p327/lib/ruby/1.9.1/net/smtp.rb:960:in 'check_auth_response': 534-5.7.14 – janosrusiczki Dec 10 '13 at 13:26
  • 3
    @kitsched check you security settings in your gmail account. Gmail is blocking suspicious activities. You need to go to the settings and confirm, that you knows the activity – w_g Jan 25 '14 at 13:16
  • @w_g Thanks, I figured it out in the meantime. At the next login it prompted me to confirm the "suspicious" activity. – janosrusiczki Jan 27 '14 at 09:21
  • this wasnt working for me in development, had to enable this setting https://www.google.com/settings/security/lesssecureapps – random-forest-cat Jan 19 '15 at 02:45