You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在使用crontab发送邮件时自定义带日期的邮件主题?

Customize Cron Email Subject with Date and Project Name

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 the date command to work correctly.
  • The date +\%Y-\%m-\%d generates a date in YYYY-MM-DD format (e.g., 2024-05-20). You can tweak the format string if you want a different style (like \%d-\%m-\%Y for 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 the mail command.

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.

  1. 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
  1. Then, add this to the end of your mongo_backup.sh script (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 10:22:52