Skip to content

Instantly share code, notes, and snippets.

@serg-kovalev
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save serg-kovalev/f0e3d01d96adb47566e8 to your computer and use it in GitHub Desktop.
Save serg-kovalev/f0e3d01d96adb47566e8 to your computer and use it in GitHub Desktop.
Sending database backup in email using core ruby
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