Skip to content

Send Email

JP Barbosa edited this page Jul 23, 2015 · 2 revisions

Send Email

Generate mailer for articles
rails g mailer ArticleMailer
Add action to mailer
nano app/mailers/article_mailer.rb
class ArticleMailer < ApplicationMailer
  def recommend(article, mail_to)
    @article = article
    mail(to: mail_to, subject: 'Article Recommendation')
  end
end
Create the view
nano app/views/article_mailer/recommend.html.erb
<p>Dear friend,</p>
<p>Check this great article: <%= url_for @article %></p>
Add action to mailer preview
nano test/mailers/previews/article_mailer_preview.rb
class ArticleMailerPreview < ActionMailer::Preview
  def recommend
    ArticleMailer.recommend(Article.first, '[email protected]')
  end
end
Change mailer config and restart the server
nano config/application.rb
...
    config.action_mailer.default_url_options = { host: ENV['HOST_NAME'] }
    config.action_mailer.delivery_method = :smtp
    config.action_mailer.smtp_settings = {
      address:              ENV['SMTP_HOST'],
      port:                 ENV['SMTP_PORT'],
      domain:               ENV['HOST_NAME'],
      user_name:            ENV['SMTP_USER'],
      password:             ENV['SMTP_PASS'],
      authentication:       'plain',
      enable_starttls_auto: true
    }
...
rails s
Check if the view is OK
open http://localhost:3000/rails/mailers/article_mailer/recommend
Change mailer config for development to raise errors
nano config/environments/development.rb
...
  # Care if the mailer can't send.
  config.action_mailer.raise_delivery_errors = true
...
Open Rails console and send a message
rails c
ArticleMailer.recommend(Article.first, '[email protected]').deliver_now
Add mailer to Git
git add .
git commit -m "Add mailer to recommend article"
Next step: Jobs Queue