You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

2 D铆as
11 Hrs
37 Min
34 Seg

Enviando e-mails a los participantes

31/36
Resources

What is the ActionMailer in Rails?

In the Ruby on Rails world, the ActionMailer is an essential module that allows you to send emails to users automatically. This tool is essential for notifying participants when, for example, a new task has been created in our application. Before you start using ActionMailer, it is important that you review the necessary data and have your development environment ready to move forward.

How to create a Mailer in Rails?

To start sending emails, we must first generate a Mailer. We will use the well known Rails generator, rails generate, parameterized with mailer. This will generate the directory and file structure needed to create the email. In this case, we will call the ParticipantMailer email system. When using the command, several directories and files are created, among them, the main ParticipantMailer file, where we will develop the logic for sending the email.

rails generate mailer ParticipantMailer

How to edit the Mailer file?

Inside the ParticipantMailer file, we can create methods as if they were controller actions. These methods are associated to views that will render the email. We are going to create a method called new_tasks_email that, by means of variables, will transmit information to the view.

class ParticipantMailer < ApplicationMailer def new_tasks_email(user, task) @user = user @task = task mail(to: @user.email, subject: 'New task assigned') endend end

How to invoke the Mailer from the task model?

It is essential to call the Mailer once a new task has been created. To achieve this, we use an after_create callback in the Task model. This callback will call the mailer method we have defined.

class Task < ApplicationRecord after_create :send_email
 private
 def send_email participants = self.participants + [self.owner] participants.each do |user| ParticipantMailer.with(user: user, task: self).new_tasks_email.deliver_later end endend end end end

How to create a view for the email?

The email view is the HTML structure that will be sent to the users. We use the new_tasks_email.html.haml file to define the content of the email.

%h1 Hello, #{@user.email}%p You have a new task:%ul %li= "Name: #{@task.name}" %li= "Description: #{@task.description}" %li= "Category: #{@task.category.name}" %li= "View task at the following link:  #{link_to 'View task', task_path(@task)}"

Previewing mails with Letter Opener

To check and preview mails without sending actual messages, we use the letter_opener gem. This gem allows to open the mails in the browser, providing a safe environment for testing and tuning.

Letter Opener Configuration

  1. Add letter_opener to the development group in your Gemfile:

    group :development do gem 'letter_opener'end
  2. Configure the development environment in config/environments/development.rb:

    Rails.application.configure do config.action_mailer.delivery_method = :letter_opener config.action_mailer.perform_deliveries = true config.action_mailer.raise_delivery_errors = true config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }end

Make sure to install the gem and restart the server:

bundle installrails server

Now, you can create a new task from your application interface and verify that the mails are generated correctly in the browser, thanks to letter_opener. This not only makes it easier to preview, but also to detect errors and style tests in your emails.

Go ahead, deepen your Rails knowledge and discover all that ActionMailer has to offer!

Contributions 4

Questions 1

Sort by:

Want to see more contributions, questions and answers from the community?

Para los que usan WSL, lamentablemente la gema letter opener no funciona por lo que se explica aqu铆.

En las recomendaciones de la gema se menciona dos alternativas, en mi caso utilic茅 MailCatcher. Para configurar esta opci贸n segu铆 los siguientes pasos:

  1. Instal茅 la gema de MailCatcher (b谩sicamente es un servidor de SMTP)
$ gem install mailcatcher
  1. Luego, en config/enviroments/development.rb agregu茅 las siguientes l铆neas (estas en total reemplazo a las que se muestran en esta clase)
config.action_mailer.default_url_options = { host: 'localhost:3000' }
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = { :address => 'localhost', :port => 1025 }
  1. Inici茅 MailCatcher con el comando
$ mailcatcher
  1. Una vez iniciado Mailcatcher, ya se puede ingresar a este servidor por medio de localhost:1080. En la interfaz que se muestra al ingresar es donde veremos los correos que se enviar谩n al crear una nueva tarea.

Excelente, como comentario; creo que la gestion de correos en ROR es una de las mas limpias que he visto, Punto positivo para ROR.

Muchas veces tengo errores por olvidar reiniciar el server y duro mucho tratando de resolver el error sin sentido haha

Con internacionalizaci贸n:

  • new_task_email.html.haml
%h1= "#{t('.hello')} #{@user.email}, #{t('.new_task_message')}"
%p
  %b= t('.name')
  = @task.name
%p
  %b= t('.description')
  = @task.description
%p
  %b= t('.category')
  = @task.category.name
%p
  %b= t('.link')
  = link_to @task.code, @task
  • es.yml
participant_mailer:
    new_task_email:
      category: Categor铆a
      description: Descripci贸n
      hello: Hola
      link: Enlace
      name: Nombre
      new_task_message: tienes una nueva tarea