You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

63 lines
2.5 KiB

  1. #!/usr/bin/env sh
  2. # Sync mail and give notification if there is new mail.
  3. # Run only if user logged in (prevent cron errors)
  4. pgrep -u "$USER" >/dev/null || exit
  5. # Run only if not already running in other instance
  6. pgrep -x mbsync >/dev/null && exit
  7. # Checks for internet connection and set notification script.
  8. ping -q -c 1 1.1.1.1 > /dev/null || exit
  9. command -v notify-send >/dev/null || echo "Note that \`libnotify\` or \`libnotify-send\` should be installed for pop-up mail notifications with this script."
  10. export DISPLAY=:0.0
  11. # Settings are different for MacOS (Darwin) systems.
  12. if [ "$(uname)" = "Darwin" ]; then
  13. notify() { osascript -e "display notification \"$2 in $1\" with title \"You've got Mail\" subtitle \"Account: $account\"" && sleep 2 ;}
  14. else
  15. notify() { notify-send "mutt-wizard" "📬 $2 new mail(s) in \`$1\` account." ;}
  16. fi
  17. # Check account for new mail. Notify if there is new content.
  18. syncandnotify() {
  19. acc="$(echo "$account" | sed "s/.*\///")"
  20. mbsync "$acc"
  21. new=$(find "$HOME/.local/share/mail/$acc/INBOX/new/" "$HOME/.local/share/mail/$acc/Inbox/new/" "$HOME/.local/share/mail/$acc/inbox/new/" -type f -newer "$HOME/.config/mutt/.mailsynclastrun" 2> /dev/null)
  22. newcount=$(echo "$new" | sed '/^\s*$/d' | wc -l)
  23. if [ "$newcount" -gt "0" ]; then
  24. notify "$acc" "$newcount" &
  25. for file in $new; do
  26. # Extract subject and sender from mail.
  27. from=$(awk '/^From: / && ++n ==1,/^\<.*\>:/' "$file" | perl -CS -MEncode -ne 'print decode("MIME-Header", $_)' | awk '{ $1=""; if (NF>=3)$NF=""; print $0 }' | sed 's/^[[:blank:]]*[\"'\''\<]*//;s/[\"'\''\>]*[[:blank:]]*$//')
  28. subject=$(awk '/^Subject: / && ++n == 1,/^\<.*\>: / && ++i == 2' "$file" | head -n-1 | perl -CS -MEncode -ne 'print decode("MIME-Header", $_)' | sed 's/^Subject: //' | sed 's/^{[[:blank:]]*[\"'\''\<]*//;s/[\"'\''\>]*[[:blank:]]*$//' | tr -d '\n')
  29. notify-send "📧$from:" "$subject" &
  30. done
  31. fi
  32. }
  33. # Sync accounts passed as argument or all.
  34. if [ "$#" -eq "0" ]; then
  35. accounts="$(awk '/^Channel/ {print $2}' "$HOME/.mbsyncrc")"
  36. else
  37. accounts=$*
  38. fi
  39. echo " 🔃" > /tmp/imapsyncicon_"$USER"
  40. pkill -RTMIN+12 i3blocks >/dev/null 2>&1
  41. # Parallelize multiple accounts
  42. for account in $accounts
  43. do
  44. syncandnotify &
  45. done
  46. wait
  47. rm -f /tmp/imapsyncicon_"$USER"
  48. pkill -RTMIN+12 i3blocks >/dev/null 2>&1
  49. notmuch new 2>/dev/null
  50. #Create a touch file that indicates the time of the last run of mailsync
  51. touch "$HOME/.config/mutt/.mailsynclastrun"