如何在使用crontab发送邮件时自定义带日期的邮件主题?
Got it, let's adjust your cron job so it sends emails with that custom subject you want. The default cron email subject is auto-generated, so we need to override how the email is sent instead of relying on cron's default behavior. Here are two straightforward methods:
Method 1: Modify the Cron Entry Directly
Update your crontab line to pipe the script's output to the mail command, which lets you specify a custom subject (including the dynamic date).
Your modified crontab will look like this:
# 1am every day (EST) 00 05 * * * /bin/bash /home/ubuntu/mongo_backup.sh | mail -s "MyProjectName Backup - $(date +\%Y-\%m-\%d)" example@gmail.com
Key Notes:
- The
\%is critical! In crontab, the%character is a special symbol (it denotes a newline), so we have to escape it with a backslash for thedatecommand to work correctly. - The
date +\%Y-\%m-\%dgenerates a date inYYYY-MM-DDformat (e.g., 2024-05-20). You can tweak the format string if you want a different style (like\%d-\%m-\%Yfor DD-MM-YYYY). - This replaces cron's default email sending, so you can remove the
MAILTO=line if you use this method—we're explicitly specifying the recipient in themailcommand.
Method 2: Handle Email Inside Your Backup Script
If you prefer to keep your crontab clean, you can add the email logic directly to your mongo_backup.sh script. This gives you more control over what's included in the email body too.
- First, update your crontab to suppress cron's default email (we'll let the script handle sending):
MAILTO=example@gmail.com # 1am every day (EST) 00 05 * * * /bin/bash /home/ubuntu/mongo_backup.sh >/dev/null 2>&1
- Then, add this to the end of your
mongo_backup.shscript (adjust the backup output capture as needed for your workflow):
# Capture the output of your backup process (replace with your actual backup command logs) BACKUP_LOG=$(tail -n 20 /var/log/mongo_backup.log) # Set the custom subject with dynamic date SUBJECT="MyProjectName Backup - $(date +%Y-%m-%d)" # Send the email with the log content echo "$BACKUP_LOG" | mail -s "$SUBJECT" "$MAILTO"
Prerequisite:
Make sure the mail utility is installed on your Ubuntu server. If not, install it with:
sudo apt update && sudo apt install mailutils
Either method will give you the custom email subject you're looking for—pick whichever fits your workflow better!
内容的提问来源于stack exchange,提问作者Profer

