Skip to content

Instantly share code, notes, and snippets.

@wyanez
Forked from emad-elsaid/mysql-backup.rb
Last active February 27, 2017 10:10
Show Gist options
  • Save wyanez/9361792 to your computer and use it in GitHub Desktop.
Save wyanez/9361792 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
#Pre-requisite: gem install mail (https://github.com/mikel/mail)
require 'mail'
mysql_username = 'root'
mysql_password = '123456'
mysql_database = 'your database' # consider use of ARGV
file_suffix = Time.new.strftime('%Y%m%d_%H%M%S')
mysql_backup_file = "backup-#{mysql_database}-#{file_suffix}.sql.gz"
user_email='xxxxx@gmail.com'
user_password='your gmail password or app specific password' #see https://support.google.com/mail/answer/1173270?hl=en
# MySql Dump and compress backup in .gz
print "Executing backup... "
cmd = "mysqldump --user=#{mysql_username} --password=#{mysql_password} #{mysql_database} | gzip -c > #{mysql_backup_file}"
ok = system(cmd)
exit(1) if !ok
print "Send backup to email... "
# Credit to :
# http://stackoverflow.com/questions/12884711/how-to-send-email-via-smtp-with-rubys-mail-gem
options = {
:address => "smtp.gmail.com",
:port => 587,
:domain => user_email,
:user_name => user_email,
:password => user_password,
:authentication => 'plain',
:enable_starttls_auto => true
}
Mail.defaults do
delivery_method :smtp, options
end
Mail.deliver do
from options[:user_name]
to options[:user_name]
subject "Database #{mysql_database} backup #{Time.new}"
body "Database #{mysql_database} backup #{Time.new}"
add_file mysql_backup_file
end
File.delete mysql_backup_file
print "Finish ok"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment