Set Up Periodic Mail Sync with cron or systemd#
Prerequisites#
mbsyncconfigured and working (see Setting Up Offline Email with mbsync).Optionally,
notmuchconfigured if you use full-text search (see Setting Up Notmuch for Email Search).Access to
cronorsystemd --useron your system.
Create a Sync Script#
Write a small wrapper script at
~/.local/bin/mailsync:
#!/bin/sh
# Sync all IMAP accounts and update the Notmuch index.
mbsync -a 2>&1
notmuch new 2>&1
Make it executable:
chmod +x ~/.local/bin/mailsync
Test it:
~/.local/bin/mailsync
Expected result: mail syncs and the Notmuch database is updated.
If you donβt use Notmuch, remove the notmuch new line.
Option A: Use cron#
Open your user crontab:
crontab -e
Add a line to run the script every 5 minutes:
*/5 * * * * ~/.local/bin/mailsync
Save and exit.
Expected result: crontab -l shows the new entry and mail syncs automatically.
Pass the GPG Passphrase in cron#
If mbsync uses pass or GPG for passwords, cron may not have access to gpg-agent.
Add environment variables to the crontab:
GPG_TTY=/dev/null
DISPLAY=:0
*/5 * * * * export GPG_TTY DISPLAY && ~/.local/bin/mailsync
Or configure gpg-agent to allow preset passphrases β see the gpg-preset-passphrase man page.
Option B: Use systemd User Timers#
Create the Service Unit#
Create
~/.config/systemd/user/mailsync.service:
[Unit]
Description=Sync mail with mbsync and update Notmuch
[Service]
Type=oneshot
ExecStart=%h/.local/bin/mailsync
Create the Timer Unit#
Create
~/.config/systemd/user/mailsync.timer:
[Unit]
Description=Run mailsync every 5 minutes
[Timer]
OnBootSec=1min
OnUnitActiveSec=5min
[Install]
WantedBy=timers.target
Enable and Start the Timer#
Reload and enable:
systemctl --user daemon-reload
systemctl --user enable --now mailsync.timer
Verify:
systemctl --user status mailsync.timer
systemctl --user list-timers
Expected result: the timer is active and mailsync.service runs every 5 minutes.
Check Logs#
journalctl --user -u mailsync.service -n 20
Expected result: recent sync output appears in the journal.
Add a Desktop Notification#
Extend
~/.local/bin/mailsyncto notify on new mail:
#!/bin/sh
mbsync -a 2>&1
notmuch new 2>&1
new_count=$(notmuch count tag:unread AND tag:inbox)
if [ "$new_count" -gt 0 ]; then
notify-send "New mail" "$new_count unread messages"
fi
Expected result: a desktop notification appears when unread mail arrives.
Trigger Sync from Inside NeoMutt#
You can still sync manually from NeoMutt alongside the timer:
macro index o "<shell-escape>~/.local/bin/mailsync<Enter>" "Sync mail now"
Expected result: pressing o runs the same sync script on demand.
See Setting Up Offline Email with mbsync for the mbsync configuration and Setting Up Notmuch for Email Search for the Notmuch setup.