Last active
July 28, 2021 13:25
-
-
Save ketanghumatkar/bbeb72934744ead291a2062f7c5e8ccf to your computer and use it in GitHub Desktop.
Send mail outside rails project with CSV attachment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 '[email protected]' | |
cc '[email protected], [email protected]' | |
from '[email protected]' | |
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