Send email in Ruby and rails through external smtp relay server

Sending email is one of those emails your web application will have to do. Whether you are sending password reset links or you are running an email newsletter, email should be integral in your application.

Ruby on rails has some great libraries for sending email. You can either sending using localhost which is a very terrible idea, a remote smtp mail server you manage (still not the best option) or use third party commercial smtp relays like gmail, mailgun, sendgrid etc which is the best option. You can read my previous post on scalable ways of sending email.

In this example, am using a remote mail server as an relay. The configurations can also be used for gmail. We use SMTP authentication schemes which means you MUST create a user account at the mail server first before you attempt sending email. Also you have to ensure that that the smtp ports you are using are open, so check with your firewall.

configure smpt in production.rb

config.action_mailer.delivery_method = :smtp

  config.action_mailer.smtp_settings = {

                                        address: 'my-remote-smpt-server',
                                        port: 587,
                                        user_name: 'user@example.com',
                                        password: 'my-secure-password',
                                        authentication: :login,
                                        enable_starttls_auto: true
                                      }
  config.action_mailer.perform_deliveries = true
  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.default_options = {from: 'user@example.com'}

mailer class

class PasswordresetMailer < ActionMailer::Base  
  default from: "no-reply@example.com"

  def send_notification
    mail to: "user@example.com", subject: "password reset"
  end
end  

Send mail

PasswordresetMailer.send_notification.deliver  

Don't forget to set the corresponding mail view of course with the actual content of the email you are sending to the end user.

David Okwii

David Okwii is a Systems Engineer who currently works with Uganda's country code top-level domain registry.

Kampala Uganda http://www.davidokwii.com

Subscribe to oquidave@geek:~ #

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!