Backup MySQL database to Gmail using PHPMailer

Sometimes client database data is so small that it is unnecessary to sign up to a dedicated 3rd party backup provider. In such cases Gmail becomes a rather useful tool for sending and storing backups as Gmail maintains a copy of all sent emails. This functionality can be achieved quite easily with PHP and PHPMailer. The script required to perform the MySQL database backup is below.

// Import mailer
require "/cms/phpmailer/class.phpmailer.php";

// Perform backup
$filename = "/tmp/" . date('Ymd-Hi') . ".sql";
exec("mysqldump -u root -p --all-databases > {$filename}");
exec("gzip $filename");
$filename .= ".gz";
$filesize = number_format(filesize($filename) / 1048576, 0);

// Send backup
$date = date('d/m/Y');
$m = new PHPMailer();
$m->SMTPAuth = true;
$m->Username = '';
$m->Password = 'password';
$m->FromName = 'Database Backup Mailer';
$m->Host = 'ssl://';
$m->Subject = "Database Backup";
$m->MsgHTML(nl2br("The Database Backup for {$date} is attached, the filesize is: {$filesize}MB."));
if ($m->Send()) {
echo "Success";
} else {
echo "Error, could not send: {$m->ErrorInfo}";

The script assumes that PHPMailer is installed in the same directory as the script in a folder called phpmailer and that MySQL has a password-less root account; change the line with mysqldump if your MySQL access details are different. Furthermore the script should be placed in folder where it can be accessed via HTTP so that you do not need to install the PHP CLI to make it work. The script can then be called using wget and added to cron to perform periodic backups.


Post a Comment