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.
 
 
 
 

67 lines
2.6 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 -xf "sh /usr/bin/mailsync.*" | wc -l)" -eq 2 ] || 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 (room for improvement).
  27. subject=$(grep "^Subject: " "$file" | sed 's/Subject: //' | head -n4)
  28. from=$(grep "^From: " "$file" | awk '{ $1=""; $NF=""; print $0 }' | tr -d "\"\'\<\>" | sed 's/^ \(.*\) $/\1/')
  29. substring="=?"
  30. # Some html emails contain weird Subject and/or Sender formatting, in which case the html tag content is used (room for improvement).
  31. [ "${subject#*$substring}" != "$subject" ] && subject=$(tr '\n' ' ' < "$file" | sed 's/.*<title>\(.*\)<\/title>.*/\1/')
  32. [ "${from#*$substring}" != "$from" ] && from=$(grep ^"From: " "$file" | sed 's/.*<\(.*\)>.*/\1/')
  33. notify-send "📧$from:" "$subject" &
  34. done
  35. fi
  36. }
  37. # Sync accounts passed as argument or all.
  38. if [ "$#" -eq "0" ]; then
  39. accounts="$(ls "$HOME/.local/share/mail")"
  40. else
  41. accounts=$*
  42. fi
  43. echo " 🔃" > /tmp/imapsyncicon_"$USER"
  44. pkill -RTMIN+12 i3blocks >/dev/null 2>&1
  45. # Parallelize multiple accounts
  46. for account in $accounts
  47. do
  48. syncandnotify &
  49. done
  50. wait
  51. rm -f /tmp/imapsyncicon_"$USER"
  52. pkill -RTMIN+12 i3blocks >/dev/null 2>&1
  53. notmuch new 2>/dev/null
  54. #Create a touch file that indicates the time of the last run of mailsync
  55. touch "$HOME/.config/mutt/.mailsynclastrun"