Exchange Online (the hosted Exchange product that is sold as part of Microsoft’s business Office 365 suite) is fast becoming a gold-standard in the business-grade email market. As a result, there are cases when a Ruby on Rails application would benefit from sending emails via the Exchange Online SMTP service.

Add the below snippet to your environment configuration file (e.g: development.rb or production.rb):

config.action_mailer.smtp_settings = {
  address:              "smtp.office365.com",
  port:                 587,
  domain:               "mydomain.com",
  user_name:            "[email protected]",
  password:             "password",
  authentication:       :login,
  enable_starttls_auto: true
}
config.action_mailer.delivery_method = :smtp

Best practices specify that the login credentials should be stored in environment variables. This keeps sensitive login credentials out of project source code.

Use the below snippet as a guide when configuring your mailer:

class ContactMailer < ApplicationMailer
  def contact_email(name, email, message)
    @name = name
	@email = email
	@message = message
    mail(to: "[email protected]", subject: "Contact from website", reply_to: @email, from: "Sender Name <[email protected]>")
  end
end

The email address the mailer sends from must match the email address used in the ActionMailer configuration's user_name field. If this doesn't match, the message will be rejected by the Exchange Online SMTP service.

Troubleshooting

If you find during testing that emails are not being sent, temporarily set ActionMailer's raise_delivery_errors option to true to help with debugging.

config.action_mailer.raise_delivery_errors = true

Leave a Reply

Your email address will not be published. Required fields are marked *