How to mail using cron
To send an email using cron, you can use the mail
command or a more advanced email client like sendmail
or ssmtp
. Here are some examples:
Using the mail
command:
- Open your crontab editor by running
crontab -e
in your terminal. - Add the following line to schedule a job to run at a specific time or interval:
*/5 * * * * mail -s "Subject" [email protected] < /path/to/email/body.txt
This will send an email with the subject "Subject" to
[email protected]
every 5 minutes. The email body will be read from the file/path/to/email/body.txt
.
Using sendmail
:
- Install
sendmail
if it's not already installed on your system. - Open your crontab editor by running
crontab -e
in your terminal. - Add the following line to schedule a job to run at a specific time or interval:
*/5 * * * * sendmail -t -i -f [email protected] < /path/to/email/body.txt
This will send an email with the contents of
/path/to/email/body.txt
to[email protected]
every 5 minutes.
Using ssmtp
:
- Install
ssmtp
if it's not already installed on your system. - Open your crontab editor by running
crontab -e
in your terminal. - Add the following line to schedule a job to run at a specific time or interval:
*/5 * * * * ssmtp -t -i -f [email protected] < /path/to/email/body.txt
This will send an email with the contents of
/path/to/email/body.txt
to[email protected]
every 5 minutes.
Tips and Variations:
- Make sure to replace
[email protected]
with the actual email address you want to send the email to. - Replace
/path/to/email/body.txt
with the actual path to the file containing the email body. - You can customize the email subject and body by modifying the
mail
command or using a more advanced email client likesendmail
orssmtp
. - You can also use environment variables or shell variables to customize the email content.
- If you're using a Linux system, you may need to use the
echo
command to format the email body as a string, like this:*/5 * * * * echo "Subject: My Email" | mail -s "My Email" [email protected]
This will send an email with the subject "My Email" and a blank body.
Remember to test your email sending configuration before scheduling the job to run automatically using cron.