/ email

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: '[email protected]',
                                        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: '[email protected]'}

mailer class

class PasswordresetMailer < ActionMailer::Base
  default from: "[email protected]"

  def send_notification
    mail to: "[email protected]", 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.

Send email in Ruby and rails through external smtp relay server
Share this

Subscribe to David Okwii dev blog