Skip to content

Sending email via Gmail SMTP

Lluís Gili edited this page Apr 22, 2016 · 5 revisions
Mail.defaults do
  delivery_method :smtp, { 
    :address => 'smtp.gmail.com',
    :port => 587,
    :user_name => ENV['GMAIL_SMTP_USER'],
    :password => ENV['GMAIL_SMTP_PASSWORD'],
    :authentication => :plain,
    :enable_starttls_auto => true
  }
end

if you are getting error "SMTP Error: 454 4.7.0 Too many login attempts, please try again later." do not authenticate for every mail, instead:

settings = {
  address:        "smtp.gmail.com",
  port:           587,
  domain:         "mydomain.com",
  user_name:      "[email protected]",
  password:       "password",
  authentication: "plain"
}

smtp_conn = Net::SMTP.new(settings[:address], settings[:port])
smtp_conn.enable_starttls_auto
smtp_conn = smtp_conn.start(settings[:domain],
                            settings[:user_name],
                            settings[:password],
                            settings[:authentication])
Mail.defaults do
  delivery_method :smtp_connection, { :connection => smtp_conn }
end

# send mails..
mail = Mail.new
mail.to('...')
# more mail stuff..
mail.deliver!

# after all mails are sent, end session
smtp_conn.finish
Clone this wiki locally