Automatically Email MySQL Database Backup

If you are in a shared hosting environment where you are responsible for your own database backups, this is a convenient way to have the server generate a backup file of all of your MySQL databases, compress the file, and email it to the specified address. I’ve added this to the local crontab so that it runs on a regular schedule. In order for it to work, you should have a MySQL user account created with the appropriate privileges in order to access your database.

In the crontab, create an entry, as follows, with your customization for both the path to your configuration file and the email address receiving the backup.

mysqldump --defaults-extra-file="/path/to/config/file/.mysqldump.cnf"
          --all-databases
          -ce
  | gzip
  | uuencode dbbackup.gz
  | /usr/sbin/sendmail my_email_address

In the .mysqldump.cnf file, provide the username and associated password that can access the database. Set the file permissions as 0600.

[client]
user=my_database_username
password=my_database_user_password

Leave a Comment