Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.