Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send MySQL backup to email with cronjob

Tags:

mysql

cron

I am trying to automatically backup my database from cPanel using a cronjob. I want to send the database to my email address when the cronjob is run and I have written code (below) but it is still not working.

mysqldump -e --user=username --password='password' dbname | gzip | uuencode sql_backup.gz | mail [email protected]

In my email when cronjob is run I am getting this message:

/usr/local/cpanel/bin/jailshell: mail: command not found
mysqldump: Got errno 32 on write

I have been referring to this article: Automatic MySQL Backup.

I hope you understand my question and help me.

I have also tried with curl but still not working. You can check my steps that I had followed.

First Step: Created mail_alert.sh file and added bellow code.

#!/bin/bash
curl --url "smtps://smtp.gmail.com:465" --ssl-reqd \
  --mail-from "[email protected]" --mail-rcpt "[email protected]" \
  --upload-file mail.txt --user "[email protected]:mypassword" --insecure

Second Step: Created mail.txt and added below code.

From: "Name" [email protected]
To: "Name" [email protected]
Subject: Backup completed

The backup has been completed.

Third Step: Added code in command line.

mysqldump -e --user=username --password='password' dbname | gzip | uuencode sql_backup.gz | sh public_html/sql/mail_alert.sh

After this I am getting this message in my mail.

curl: option --ssl-reqd: is unknown
curl: try 'curl --help' or 'curl --manual' for more information
mysqldump: Got errno 32 on write
like image 352
lumos Avatar asked Oct 29 '25 08:10

lumos


1 Answers

Looks like mail is not available for you to use or is not installed.

Another option to consider is to using curl to send emails as described here: https://stackoverflow.com/a/16069786/280842

Here's how you could implement this, using code from the link above:

mail_alert.sh file contents

#!/bin/bash
curl --url "smtps://smtp.gmail.com:465" --ssl-reqd \
  --mail-from "[email protected]" --mail-rcpt "[email protected]" \
  --upload-file mail.txt --user "[email protected]:password" --insecure

mail.txt file contents

From: "User Name" <[email protected]>
To: "John Smith" <[email protected]>
Subject: Backup completed

The backup has been completed.

It's considered a bad security practice to pass account credentials thru command line arguments. The above example is for demo purpose only.

Then add your newly created script to your existing cron job

mysqldump -e --user=username --password='password' dbname | gzip | uuencode sql_backup.gz | sh /home/myuser/mail_alert.sh
like image 113
filype Avatar answered Oct 31 '25 01:10

filype



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!