Last active
August 29, 2015 14:18
-
-
Save serg-kovalev/f0e3d01d96adb47566e8 to your computer and use it in GitHub Desktop.
Sending database backup in email using core ruby
This file contains 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
require 'net/smtp' | |
FROM = 'Some name <name@email.me>' | |
TO = %w(name@email.me) | |
SUBJ = "DB backup #{Time.now.strftime('%Y-%m-%d')}" | |
# find the last (in 60 mins) backup | |
filename = `find /path/to/backups/*.sql.gz -mmin -60`.chomp | |
exit if filename.nil? || filename.empty? | |
# Read a file and encode it into base64 format | |
filecontent = File.read(filename) | |
encodedcontent = [filecontent].pack("m") # base64 | |
marker = 'SOMEUNIQMARKER' | |
body =<<EOF | |
Please find DB backup in attachment. | |
EOF | |
# Define the main headers. | |
part1 =<<EOF | |
From: #{FROM} | |
To: #{TO.join(';')} | |
Subject: #{SUBJ} | |
MIME-Version: 1.0 | |
Content-Type: multipart/mixed; boundary=#{marker} | |
--#{marker} | |
EOF | |
# Define the message action | |
part2 =<<EOF | |
Content-Type: text/plain | |
Content-Transfer-Encoding:8bit | |
#{body} | |
--#{marker} | |
EOF | |
# Define the attachment section | |
part3 =<<EOF | |
Content-Type: multipart/mixed; name=\"#{filename}\" | |
Content-Transfer-Encoding:base64 | |
Content-Disposition: attachment; filename="#{filename}" | |
#{encodedcontent} | |
--#{marker}-- | |
EOF | |
mailtext = part1 + part2 + part3 | |
# Let's put our code in safe area | |
begin | |
Net::SMTP.start('localhost') do |smtp| | |
smtp.sendmail(mailtext, FROM, TO) | |
end | |
rescue Exception => e | |
print "Exception occured: " + e | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment