· 8 years ago · Mar 02, 2018, 08:38 AM
1#!/usr/bin/env ruby
2
3##
4# Run ruby script outside rails project by loading rails env
5# Script will sent mail with csv attachment and run through cronjob
6# Steps :-
7# 1. Load rails environment
8# 2. Set Mail SMTP configuration
9# 3. Generate CSV
10# 4. Configure mail
11# 5. Send mail
12# 6. Setup cronjob
13##
14
15# Load rails environment
16require './config/environment'
17
18## SMTP configuration
19Mail.defaults do
20 delivery_method :smtp, {
21 user_name: 'sendgrid user_name',
22 password: 'sendgrid password',
23 domain: 'gmail.com',
24 address: 'smtp.sendgrid.net',
25 port: 587,
26 authentication: 'plain',
27 enable_starttls_auto: true
28 }
29end
30
31## Generate CSV
32 csv_string = CSV.generate do |csv|
33 csv << ['C1', 'C2']
34 csv << ['d1', 'd2']
35end
36
37## Configure mail
38mail = Mail.new do
39 to 'ketan@example.com'
40 cc 'xyz@foo.com, pqr@foo.com'
41 from 'no-reply@foo.com'
42 subject 'Email subject'
43 add_file :filename => 'filename.csv', :content => csv_string
44end
45
46## Send mail
47mail.deliver!
48
49## Setup cronjob
50# 1. crontab -e
51# 2. 30 5 * * * /bin/bash -l -c 'cd /var/www/rails_project/current && RAILS_ENV=development ruby /home/user/scripts/script1.rb'
52# Run job daily at 11:30 AM IST