0

我有一个 BASH 脚本,如下所示:

cat limit_mail.out | while read num email limit orders; do
    echo "Sending mail to '$email'"
    printf "$email_template" "$email" "$num" "$limit" "$orders" |
    sendmail -oi -t
done

我怎样才能使它在发送电子邮件时将电子邮件地址与日期和时间一起保存在文本文件中,然后检查以确保没有电子邮件地址在 24 内收到超过 1 封电子邮件小时?

4

2 回答 2

2

一种方法是为每个收件人创建一个文件,并使用文件的时间戳。

MAIL_TIMESTAMPS=/var/cache/mailstamps
mkdir "$MAIL_TIMESTAMPS"

cat limit_mail.out | while read num email limit orders; do
    echo "Sending mail to '$email'"
    email_hash="$(md5sum <<< "$email" | cut -d' ' -f1)";
    # Check that a timestamp file doesn't exist, or that it was modified over 24h ago
    if ! test -n "$(find "$MAIL_TIMESTAMPS" -mtime -1 -name "$email_hash")"; then
      touch "$MAIL_TIMESTAMPS/$email_hash" # Update timestamp
      printf "$email_template" "$email" "$num" "$limit" "$orders" |
      sendmail -oi -t
    fi
done

编辑:我添加了电子邮件地址的散列。无论如何,这是我打算做的事情,但是Aleks-Daniel 的代码非常简洁明了,我在这里借用了它,仅从 sha256sum 更改为 md5sum。MD5 更快,虽然它有潜在的问题,但我不认为它们在这里会成为问题(当然你可以自由选择)。散列还避免了特殊字符扰乱 find 的文件名匹配的问题。

于 2013-09-02T12:32:09.407 回答
1

在文件中使用时间戳:

DELAY_FOLDER='myTempFolder/'
DELAY=$((24*60*60)) # one day

while read num email limit orders; do
    echo "Sending mail to '$email'"
    if [[ -f $DELAY_FOLDER/$email ]] && (( $(cat "$DELAY_FOLDER/$email") + DELAY > $(date +%s) )); then
        echo "email has been sent already"
    else
        printf "$email_template" "$email" "$num" "$limit" "$orders" | sendmail -oi -t
        echo "$(date +%s)" > "$DELAY_FOLDER/$email"
    fi
done < limit_mail.out

此外,如果您不希望任何人看到临时文件夹中的电子邮件地址,您可以使用 md5 或 sha sum 来覆盖您的地址。像这样:

DELAY_FOLDER='myTempFolder/'
DELAY=$((24*60*60)) # one day

while read num email limit orders; do
    echo "Sending mail to '$email'"
    emailsha=$(sha256sum <<< "$email" | cut -d' ' -f1)
    if [[ -f $DELAY_FOLDER/$emailsha ]] && (( $(cat "$DELAY_FOLDER/$emailsha") + DELAY > $(date +%s) )); then
        echo "email has been sent already"
    else
        printf "$email_template" "$email" "$num" "$limit" "$orders" | sendmail -oi -t
        echo "$(date +%s)" > "$DELAY_FOLDER/$emailsha"
    fi
done < limit_mail.out
于 2013-09-02T12:44:45.927 回答