Skip to content

Instantly share code, notes, and snippets.

@ketanghumatkar
Last active July 28, 2021 13:25
Show Gist options
  • Save ketanghumatkar/bbeb72934744ead291a2062f7c5e8ccf to your computer and use it in GitHub Desktop.
Save ketanghumatkar/bbeb72934744ead291a2062f7c5e8ccf to your computer and use it in GitHub Desktop.
Send mail outside rails project with CSV attachment
#!/usr/bin/env ruby
##
# Run ruby script outside rails project by loading rails env
# Script will sent mail with csv attachment and run through cronjob
# Steps :-
# 1. Load rails environment
# 2. Set Mail SMTP configuration
# 3. Generate CSV
# 4. Configure mail
# 5. Send mail
# 6. Setup cronjob
##
# Load rails environment
require './config/environment'
## SMTP configuration
Mail.defaults do
delivery_method :smtp, {
user_name: 'sendgrid user_name',
password: 'sendgrid password',
domain: 'gmail.com',
address: 'smtp.sendgrid.net',
port: 587,
authentication: 'plain',
enable_starttls_auto: true
}
end
## Generate CSV
csv_string = CSV.generate do |csv|
csv << ['C1', 'C2']
csv << ['d1', 'd2']
end
## Configure mail
mail = Mail.new do
to 'ketan@example.com'
cc 'xyz@foo.com, pqr@foo.com'
from 'no-reply@foo.com'
subject 'Email subject'
add_file :filename => 'filename.csv', :content => csv_string
end
## Send mail
mail.deliver!
## Setup cronjob
# 1. crontab -e
# 2. 30 5 * * * /bin/bash -l -c 'cd /var/www/rails_project/current && RAILS_ENV=development ruby /home/user/scripts/script1.rb'
# Run job daily at 11:30 AM IST
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment