How to send daily email?

Asked

Viewed 984 times

2

I have an application in Ruby on Rails that I need to send a daily email. I thought to use the own class Mailer of rails. What I do not know is if it is possible to check the time to perform automated sending using the rails.

It is possible to use a timer to make this check and fire the sending method at a certain time? If not, is there any Gem that performs this job?

  • I don’t know Rails and its servers, but on Linux servers for PHP you can use Cron Jobs. I found this for Rails, see if it helps you: Whenever

  • @user157930 Daria just to explain the use of Whenever?

1 answer

2


Next @Felipe I have a linux server with 4 Rails applications running on it. And also a ruby application that triggers a few emails a day, this ruby application is small and uses the Actionmailer for sending emails and has a crontab job running a few times a day. I will put an example of this application here very simplified.

It stays in the directory /var/www/mensageria inside it I have the following files:

  • mailer_config.Rb (smtp Directory settings, password user etc)
  • notification_mailer.Rb (Class Mailer)
  • send.Rb (File that fires the email)

And there’s a folder called notification_mailer and within it a file alert.html.erb.

In the archive mailer_config.rb has the following code:

ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
    address:                "smtp.gmail.com",
    port:                   587,
    domain:                 "domain.com.br",
    authentication:         :plain,
    user_name:              "user",
    password:               "password",
    enable_starttls_auto:   true
}

In the archive notification_mailer.rb has the following code:

require 'rubygems'
require 'action_mailer'
require 'action_view'
require './mailer_config.rb'

class NotificationMailer < ActionMailer::Base
    default from: 'Nome do Remetente <[email protected]>'
    def alert(to,subject)
        mail(to: to, subject: subject) do |format|
            format.html { render './notification_mailer/alert.html.erb' }
        end
    end
end

In the archive send.rb has the following code:

require './notification_mailer.rb'
NotificationMailer.alert('[email protected]','Teste de Email').deliver

The archive alert.html.erb you place the content to be sent.

Ai now only the crontab is missing. In a terminal on the server run:

crontab -e you can edit as if you were editing a file by vim

0 6 * * * /bin/bash -l -c 'cd /var/www/mensageria && ruby send.rb'

With that he will execute the send.rb every day at 06:00.

  • I would only add to that reply the possibility of using Gem Whenever, which facilitates working with the crontab. Other than that, that answer helped me a lot.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.