Package: imaparms
What isimaparms?imaparmsis ahandySwiss-army-knife-like tool/utility/console app for POSIX-compatible systems that can help you to download/fetch/backup all your mail/email from an IMAP server (e.g. GMail, Yahoo, Hotmail, Yandex, etc, or your own private mail server) to your hard disk, programmatically change flags on messages on the IMAP server (e.g. mark all messages newer than a day old in some folder as unread), delete/expire old messages from the IMAP server, and similar.Or, more formally:imaparmsis a utility for fetching and performing batch operations on messages residing on IMAP servers.
That is: login to a specified server, fetch or perform specified actions (count, flag/mark, delete, etc) on all messages matching specified criteria in all specified folders, logout.Or, in comparison to other things,imaparmsis an advanced but fairly KISS (Keep It Stupid Simple) replacement for a combination offetchmail/getmailandIMAPExpire, with additional features, and written in pure Python.
Also, it fetches mail >150 times faster and (when using--maildiroption) generates ~150 times less disk writes thanfetchmailandgetmailby default, and it is designed to do its very best at not losing any of your mail regardless of network connections failing unexpectedly, your IMAP server generating errors at unexpected times, other simultaneous IMAP clients making incompatible changes that could lead to future data loss, your disk failing whileimaparmstries tofsyncyour data, and you callingimaparmswith wrong command line arguments.ScreenshotClick the above image to see the full terminal recording video ofimaparmsinvocation (with account data edited out and replaced by fake GMail accounts in post-processing) runningnew-mail-hookindexing new mail withnotmuch(see workflow example below), followed by a full-text search in Emacs UI ofnotmuch.It was recorded on a 2013-era laptop (Thinkpad X230 with Intel Core i5-3230M CPU @ 2.60GHz upgraded with 16GB RAM and Samsung 870 EVO SSD), mynotmuchdatabase contains ~4 millions messages, and the whole search takes only 0.25 seconds in person (but about 2 seconds in the video because rendering anasciinemafile to gif and then compressing it into webm adds extra time between frames, so it looks much more laggy than it actually is at the end there).Why doesimaparmsexist?If all your email experience can be summarized as "I do all my mail in GMail or similar" or if you don't know what aMaildiris,you should start withthis section belowto learn why you might want to do the following.If youfetch all your mail into aMaildirwithfetchmail,getmail, or similar,index it withsup,notmuch, or similar, and thenbackup your index and tags/labels database with a generic file synchronization tool likesyncthing,bup,rsync,git, or similar... effectively, you are using IMAP as a mail delivery protocol, not like a mail access protocol it was designed to be.In which case you might ask yourself, wouldn't it be nice if there was a tool that could help you automate fetching of new messages and deletion of already backed up old messages from IMAP servers in such a way thatany of your own systems crashing or losing hard drives at any point in time would not lose any of your mail?imaparmsis a replacement forfetchmail/getmailthat does this (and more, but mainly this).Why would you make a replacement forfetchmail/getmail?imaparmswas inspired byfetchmailandIMAPExpireand is basically asafegeneralized combination of the two.I used to use and (usually privately, but sometimes not) patch bothfetchmailandIMAPExpirefor years before getting tired of it and deciding it would be simpler to just write my own thingy instead of trying to makefetchmailfetch mail at decent speeds and fix all the issues making it unsafe and inconvenient to runIMAPExpireimmediately afterfetchmailfinishes fetching mail.
The main problem is thatfetchmailfetches yet-unfetchedmail, whileIMAPExpireexpiresoldmail.
Whenfetchmailgets stuck or crashes it is entirely possible forIMAPExpireto delete some old yet-unfetched messages.
(Andgetmailsuffers from exactly the same problems.)In short,imaparmsis designed to be used as a IMAP-server-to-local-MaildirMail Delivery Agent(MDA) that makes the IMAP server in question store as little mail as possible while preventing data loss.Which is to say, the main use case I made this for is as follows:you periodically fetch your mail to a localMaildirwith this tool'simaparms fetchsubcommand (which does whatfetchmail --softbounce --invisible --norewrite --mda MDAdoes but much faster), thenyou backup yourMaildirwithsyncthing/bup/rsync/git/etc to make at least one other copy somewhere, and then, after your backup succeeds,you run this tool'simaparms deletesubcommand to expire old already-fetched messages from the server (I prefer to expire messages--older-thansome number of intervals between backups, just to be safe, but if you do backups directly after thefetch, or you like to live dangerously, you could delete old messages immediately), so thatwhen/if your account get cracked/hacked the attacker only gets your unfetched mail (+ configurable amount of yet to be removed messages), which is much better than them getting the whole last 20 years or whatever of your correspondence. (If your personal computer gets compromised enough, attackers will eventually get everything anyway, so deleting old mail from servers does not make things worse. But see some more thoughts on this below.)Also,imaparmsseems to be one of the fastest, if not the fastest, IMAP fetchers there is.
By default, it fetches mail >150 times faster thanfetchmail(andgetmail), but if your IMAP server supports long enough command lines, your system can do SSL and your hard drive can flush data fast enough, then you can saturate a gigabit Ethernet link withimaparms.Since bootstrapping into a setup similar to the one described above requires querying into actual IMAP folder names and mass changes to flags on IMAP server-side,imaparmsprovides subcommands for that too.See the "subcommands" subsection of theusage sectionfor the list available of subcommands and explanations of what they do.QuickstartInstallationInstall with:pip install imaparmsand run asimaparms --helpAlternatively, install it via Nixnix-env -i -f ./default.nix
imaparms --helpAlternatively, run without installing:alias imaparms="python3 -m imaparms"
imaparms --helpHow to: backup all your mail from GMail, Yahoo, Hotmail, Yandex, etcimaparmsis notintendedas anIMAP mirroring tool, it is intended to be used as aMail Delivery Agent with automatic expiration of old server-side mail, i.e. a better replacement forfetchmail+IMAPExpirecombination.
If you want to keep a synchronized copy of your mail locally and on your mail server without sacrificing any flags, you should useofflineimap,imapsync, or something similar instead.However,imaparmscan be used for efficient incremental backups of IMAP server data if you are willing to sacrifice either ofSEENorFLAGGED("starred") IMAP flags for it.
Also, making email backups withimaparmsis pretty simple,useful, and illustrative, so a couple of examples follow.How to: fetch all your emails from GMail, Yahoo, Hotmail, Yandex, etcThe following will fetch all messages from all the folders on the server (without changing message flags on the server side) and just put them all into~/Mail/backupMaildir(creating it if it does not exists).# backup all your mail from GMail
imaparms fetch --host imap.gmail.com --user account@gmail.com --pass-pinentry \
  --maildir ~/Mail/backup --all-folders --any-seenFor GMail you will have to create and use application-specific password, which requires enabling 2FA,see below for more info.Also, if you have a lot of mail, this will be very inefficient, as it will try to re-download everything again if it ever gets interrupted.How to: efficiently incrementally backup all your mail from GMail, Yahoo, Hotmail, Yandex, etcTo make the above efficient you have to sacrifice eitherSEENorFLAGGEDIMAP flags to allowimaparmsto track which messages are yet to be fetched, i.e. either:# mark all messages as UNSEEN
imaparms mark --host imap.gmail.com --user account@gmail.com --pass-pinentry \
  --folder "[Gmail]/All Mail" unseen

# fetch UNSEEN and mark as SEEN as you go
# this can be interrrupted and restarted and it will continue from where it left off
imaparms fetch --host imap.gmail.com --user account@gmail.com --pass-pinentry \
  --maildir ~/Mail/backup --folder "[Gmail]/All Mail" --unseenor# mark all messages as UNFLAGGED
imaparms mark --host imap.gmail.com --user account@gmail.com --pass-pinentry \
  --folder "[Gmail]/All Mail" unflagged

# similarly
imaparms fetch --host imap.gmail.com --user account@gmail.com --pass-pinentry \
  --maildir ~/Mail/backup --folder "[Gmail]/All Mail" --any-seen --unflaggedThis, of course, means that if you open or "mark as read" a message in GMail's web-mail UI while using--unseen, or mark it as flagged ("star") it there while using--unflagged,imaparmswill ignore the message on the nextfetch.How to: efficiently incrementally backup millions and/or decades of messages from GMail, Yahoo, Hotmail, Yandex, etcIn cases where you want to fetchmillionsof messages spanningdecades, you'll probably want invokeimaparms fetchmultiple times with progressively smaller--older-thanarguments so that IMAPSEARCHcommand responses will be smaller to re-fetch if the process gets interrupted, i.e.:# mark all messages as UNSEEN
imaparms mark --host imap.gmail.com --user account@gmail.com --pass-pinentry \
  --folder "[Gmail]/All Mail" unseen

for n in 10 5 3 2 1; do
    echo "fetching mail older than $n years..."
    imaparms fetch --host imap.gmail.com --user account@gmail.com --pass-pinentry \
      --maildir ~/Mail/backup --folder "[Gmail]/All Mail" --unseen \
      --older-than $((365*n))
doneWhat do I do with the resultingMaildir?You feed it intosup,notmuch, or similar, as discussedthis section, and it gives you a GMail-like UI with full-text search and tagging, but with faster search, with no cloud storage involvement, and it works while you are offline.Or you just repeat this mirroring on a schedule so thatwhen/if GMail decides to take your mail hostageyou will be prepared to switch.Can I use an MDA/LDA to deliver messages?Yes, just replace--maildir DIRECTORYwith--mda MDA.
For instance, formaildropMail Delivery Agent (also knows as Local Delivery Agent, LDA, as it is an MDA that gets used to deliver messages to same machine) fromCourier Mail Server project--- which is a commodity MDA/LDA with the simplest setup, that I know of --- the simplestimaparms fetchinvocation looks like this:### setup: do once
mkdir -p ~/Mail/backup/{new,cur,tmp}

cat > ~/.mailfilter << EOF
DEFAULT="\$HOME/Mail/backup"
EOF

# backup all your mail from GMail
imaparms fetch --host imap.gmail.com --user account@gmail.com --pass-pinentry \
  --mda maildrop --all-folders --any-seenOf course, you can use any other MDA/LDA you want, e.g.:fdmcan function as an LDA and it is also pretty simple to setup;deliveries to an SMTP server can be done by usingmsmtp.How to: implement "fetch + backup + expire" workflowThe intended workflow describedabovelooks like this:### setup: do once
echo 0 > ~/.rsync-last-mail-backup-timestamp

cat > ~/bin/new-mail-hook << EOF
#!/bin/sh -e
# index new mail
notmuch new

# auto-tagging rules go here

# backup
backup_start=\$(date +%s)
if rsync -aHAX ~/Mail /disk/backup ; then
    echo "\$backup_start" > ~/.rsync-last-mail-backup-timestamp
fi
EOF
chmod +x ~/bin/new-mail-hook### repeatable part

# optionally, if needed
# imaparms mark ... --folder "[Gmail]/All Mail" unseen

# every hour, fetch new and expire old mail from two GMail accounts,
# generate new desktop notifications with `notify-send` if some of the commands fail
imaparms for-each --every 3600 --notify-failure \
    --host imap.gmail.com \
      --user account@gmail.com --passcmd "pass show mail/account@gmail.com" \
      --user another@gmail.com --passcmd "pass show mail/another@gmail.com" \
  -- \
    fetch --folder "[Gmail]/All Mail" --maildir ~/Mail/INBOX --new-mail-cmd new-mail-hook \; \
    fetch --folder "[Gmail]/Spam" --maildir ~/Mail/spam  \; \
    delete --folder "[Gmail]/All Mail" --folder "[Gmail]/Spam" --folder "[Gmail]/Trash" \
      --older-than-timestamp-in ~/.rsync-last-mail-backup-timestamp \
      --older-than 7

# note how new spam does not invoke `new-mail-hook`You can check your command lines by running with--very-dry-runoption, for the command above it prints:# every 3600 seconds, for each of
... user account@gmail.com on host imap.gmail.com port 993 (SSL)
... user another@gmail.com on host imap.gmail.com port 993 (SSL)
# do
... in '[Gmail]/All Mail': search (UNSEEN), perform fetch, mark them as SEEN
... in '[Gmail]/Spam': search (UNSEEN), perform fetch, mark them as SEEN
... in '[Gmail]/All Mail', '[Gmail]/Spam', '[Gmail]/Trash': search (SEEN BEFORE 1-Jan-1970) {dynamic}, perform deletePersonally, I have a separate scriptexec-invokingimaparms(see the terminal recording above) for each mail service I use, my window manager spawns a terminal window withtmux attach -t subson startup while I have the following at the end of my~/.tmux.conf:# create new session named "subs" with the first window named "shell"
new-session -s subs -n shell
# set remain-on-exit for all windows in this session by default
set-option  -t subs -g remain-on-exit on
# add new windows running imaparms instances
new-window -t :2 -n mail imaparms-fetch-mine
new-window -t :3 -n gmail imaparms-fetch-gmail
# ... and so onThis way, if I need to fetch mail from one of the services immediately (e.g. for 2FA tokens sent via email) I just navigate to the respectivetmuxwindow and hitCtrl+Cthere.How to: runimaparmsin parallel withfetchmailor similarYou can runimaparms fetchwith--any-seen --unflaggedcommand line options instead of the implied--unseen --any-flaggedoptions, which will make it use theFLAGGEDIMAP flag instead of theSEENIMAP flag to track state, allowing you to run it simultaneously with tools that use theSEENflag, likefetchmail,getmail, or just another instance ofimaparms(using the other flag).I.e. if you are really paranoid, you can this feature to check files produced byfetchmailandimaparms fetchagainst each other and then simply delete duplicated files.
Or you can use it to run two instances ofimaparmson two separate machines and only expire old mail from the server after it was successfully backed up onto both machines.Running in parallel withfetchmailusingmaildropMDA for bothfetchmailandimaparmscan be implemented like this:### setup: do once
echo 0 > ~/.rsync-last-mail-backup-timestamp

mkdir -p ~/Mail/INBOX/{new,cur,tmp}
mkdir -p ~/Mail/spam/{new,cur,tmp}
mkdir -p ~/Mail/INBOX.secondary/{new,cur,tmp}

cat > ~/.mailfilter << EOF
DEFAULT="\$HOME/Mail/INBOX"
EOF

cat > ~/.mailfilter-spam << EOF
DEFAULT="\$HOME/Mail/spam"
EOF

cat > ~/.mailfilter-secondary << EOF
DEFAULT="\$HOME/Mail/INBOX.secondary"
EOF

cat > ~/bin/new-mail-hook-dedup << EOF
#!/bin/sh -e
# deduplicate
jdupes -o time -O -rdN ~/Mail/INBOX ~/Mail/INBOX.secondary

# continue as usual
exec ~/bin/new-mail-hook
EOF
chmod +x ~/bin/new-mail-hook-dedup

secondary_common=(--host imap.gmail.com \
  --user account@gmail.com --passcmd "pass show mail/account@gmail.com" \
  --user another@gmail.com --passcmd "pass show mail/another@gmail.com")

# prepare by unflagging all messages
imaparms mark "${secondary_common[@]}" --folder "INBOX" unflagged### repeatable part
# run fetchmail daemon as usual, fetching new mail into the secondary maildir every hour
fetchmail --mda "maildrop ~/.mailfilter-secondary" -d 3600

# every 15 minutes
# - fetch new mail using FLAGGED flag for tracking state from "[Gmail]/All Mail",
# - fetch new mail using SEEN flag for tracking state from "[Gmail]/Spam",
# - expire old backed up messages marked both SEEN (by fetchmail) and FLAGGED (by imaparms) from "[Gmail]/All Mail",
# - expire old backed up messages marked as SEEN (by imaparms) from "[Gmail]/Spam",
# - clean any messages older than 7 days (regardless of their flags) from "[Gmail]/Trash".
# - generate new desktop notifications with `notify-send` if some of the commands fail
imaparms for-each --every 900 --notify-failure \
    "${secondary_common[@]}" \
  -- \
    fetch --folder "[Gmail]/All Mail" --mda maildrop --new-mail-cmd new-mail-hook --any-seen --unflagged \; \
    fetch --folder "[Gmail]/Spam" --mda "maildrop ~/.mailfilter-spam" \; \
    delete --seen --flagged --folder "[Gmail]/All Mail" \
      --older-than-timestamp-in ~/.rsync-last-mail-backup-timestamp \
      --older-than 7 \; \
    delete "[Gmail]/Spam" \
      --older-than-timestamp-in ~/.rsync-last-mail-backup-timestamp \
      --older-than 7 \; \
    delete --any-seen --any-flagged --folder "[Gmail]/Trash" \
      --older-than 7

# note how new spam does not invoke `new-mail-hook`See alsoSee theusage sectionfor explanation of used command line options.See theexamples sectionfor more examples.Why would you even want to use any of this, isn't GMail good enough?Remember the time when YouTube and Facebook showed you only the posts of people you were subscribed to?
After they locked your in by becoming a monopoly by providing fairly good social networking services for free for years (selling under cost is textbook monopolistic behaviour) they started showing "promoted" posts (i.e. advertisements) in your feed so that they could provide cheap and very effective advertisement services for companies at your expense.
Then, when advertisers were locked in, they started fleecing them too.Now your subscriptions are just one of the inputs to theiralgorithms that are designed to make you waste as much time as possibleon their platforms (while keeping you satisfied or addicted just enough so that you wouldn't just leave), and advertisers' ad postings are just inputs to their algorithms that are designed to waste as much of the advertiser's money as possible (being just effective enough to make them spend more).(The process which Cory Doctorow calls "Enshittification".)Remember the time when most people run their own mail servers or had their employers run them and you yourself got to decide which messages should go toINBOXand which should be marked as spam?
Today, Google provides email services for free, and so >70% of all e-mails originate from or get delivered to Google servers (GMail, GMail on custom domains, corporate GMail).
Now it's Google who decides which messages you get to see and which vanish into the void without a trace.Which, as a recipient, is highly annoying if you frequently get useful mail that GMail marks as spam or just drops (happens all the time to me).
And, as a sender, is highly annoying when you need to send lots of mail.
Just go look up "Gmail Email Limits" (on a search engine other than Google).
It's a rabbit hole with lots of ad-hoc rules on just how much mail you can send before GMail decides to just drop your messages, yes,drop, not mark as spam, not reject,they will drop your mail and tell neither you nor the recipient anything at all.Moreover, they are now working towards making theirINBOXinto analgorithmically generated feed with "important" messages being shown first.
It's easy to see where this is going.Luckily,while Google is working hard to discourage you from using and/or make open mail protocols unusable, IMAP is still #1 protocol for accessing and managing mail, and setting up your own mail server gets easier every year, so they can't just stop supporting it just yet (but they are doing their best).But, objectively, GMail --- when it works --- is a very niceMail User Agent(aka MUA, aka email client, aka mail app) with an integrated full-text search engine and a labeling system.Meanwhile, other modern MUAs likeThunderbird,Sylpheed, orK-9 Mailare designed to be IMAP and SMTP clientsfirst, full-text search and tagging/labeling systemssecond(if at all).
Which is to say, they suck at searching and tagging mail.
Especially, since doing those things over IMAP is annoyingly slow, especially when your IMAP server is GMail which very much does not want you to use IMAP (after all, with a MUA working over IMAP, it's the MUA that decides how to sort and display yourINBOX, not Google, and they hate they can't turn the order of messages in yourINBOXinto something they can sell).However, there exists a bunch of MUAs that can do full-text mail search and tagging so well and so blazingly fast that they leave GMail in the dust (from a technical standpoint, given an index, full-text search >10x faster than GMail on a single-core of 2012-era laptop with an SSD is pretty easy to archive, simply because your SSD is much closer to you than GMail's servers).Examples of such awesome MUAs that I'm aware of, in the order from simplest to hardest to setup:sup(also this) as both MUA and mail indexer,alotas MUA +notmuchas mail indexer,Emacs UI ofnotmuchas MUA +notmuchas mail indexer,Muttas MUA +notmuchas mail indexer.However, to use these awesome MUAs you need to download your mail and save it inMaildirformaton your hard disk first.Which is whereimaparmsand similar tools likefetchmail,getmail,offlineimap,imapsync, and etc come in.Also, if GMail suddenly decides to take your mail hostage by locking you into their web-mail and disabling IMAP access,which seems more and more plausible every year, having a local copy of most of your mail will make it much easier to switch away.
(Seems unrealistic to you?
This actually happened to me with one of the email providers I used before (not GMail,not yet).
They basically tried to force me to go through a KYC procedure to allow me to continue using IMAP, but because I had local backups, I just switched all the services that referenced that email address to something else and simply stopped using their service.
Are you sure Google wouldn't do this?)See"The Homely Mutt" by Steve Loshfor a long in-detail explanation on how this setup in general is supposed to work.
It describes a setup specifically tailored formutt+notmuch+offlineimap+msmtpand the actual configs there are somewhat outdated (it was written in 2012) and much more complex than what you would need with, e.g.sup+imaparms+msmtp, but it gives a good overview of the idea in general.
Functionally,imaparmstakes placeofflineimapin that article.Personally, I usenotmuchwith Emacs, which requires almost no setup if you have a well-configured Emacs already (and effectively infinite amounts of setup otherwise).Also, see"Sup" article on ArchWikifor how to setupsup.(Also, in theory,Thunderbirdalso supports operation overMaildir, but that feature is so buggy it's apparently disabled by default at the moment.)Google's security theaterGMail docs say that IMAP and SMTP are "legacy protocols" and are "insecure".
Which, sure, they could be, if you reuse passwords.
But them implying that everything except their own web-mail UI is "insecure" is kinda funny given that they do use SMTP to transfer mail between servers andsigning in with Google promptsexists.
I.e. you can borrow someone's phone, unlock it (passcode? peek over their shoulder or just get some video surveillance footage of them typing it in public; fingerprint? they leave their fingerprints all over the device itself, dust with some flour, take a photo, apply some simple filters, 3D-print the result, this actually takes ~3 minutes to do if you know what you are doing), ask Google to authenticate via prompt.
Done, you can login to everything with no password needed.
And Google appears to give no way to disable Google prompts if your account has an attached Android device.
Though, you can make Google prompts ask for a password too, but that feature needs special setup.
Meanwhile, "legacy" passwords are not secure, apparently?So to useimaparmswith GMail you will have to enable 2FA in your account settings and then add an application-specific password for IMAP access.
I.e., instead of generating a random password and giving it to Google (while storing it in a password manager that feeds it toimaparms), you ask Google to generate a random password for you and use that withimaparms.To enable 2FA, even for very old accounts that never used anything phone or Android-related, for no rational reasons, GMail requires specifying a working phone number that can receive SMS.
Which you can then simply remove after you copied your OTP secret into an authenticator of your choice.
Sorry, why did you need the phone number, again?Ah, well, Google now knows it and will be able track your movements by buying location data from your network operator.
Thank you very much.In theory, as an alternative to application-specific passwords, you can setup OAuth2 and update tokens automatically withmailctl, but Google will still ask for your phone number to set it up, and OAuth2 renewal adds another point of failure without really adding any security if you store your passwords in a password manager and use--passcmdoption described below to feed them intoimaparms.That is to say, I don't use OAuth2, which is whyimaparmsdoes not support OAuth2.Your emails will eventually get stolen anywayNote thatSnowden revelationsmean that Google and US Government store copies of all of your correspondence since 2007-2009 (it depends on your mail provider) even if you delete everything from all the servers.And they wiretap basically all the traffic going though international Internet exchanges because they wiretap all underwater cables.
Simply because they can, apparently?
(If you think about it, there is absolutely no point to doing this if you are trying to achieve their stated signal-intelligence goals.
Governments and organized crime use one-time-pads since 1950s.
AES256 + 32 bytes of shared secret (+ 8 bytes of plain-text session key + 4 bytes of plain-text IV) + some simplesteganographyand even if the signal gets discovered, no quantum-computer will ever be able to break it, no research intoquantum-safe cryptographyneeded.
So, clearly, this data collection only works against private citizens and civil society which have no ways to distribute symmetric keys and thus have to use public-key cryptography.)Globally, >70% of all e-mails originate from or get delivered to Google servers (GMail, GMail on custom domains, corporate GMail).Most e-mails never gets E2E-encrypted at all,(100 - epsilon)% (so, basically, 100%) of all e-mails sent over the Internet never get encrypted with quantum-safe cryptography in-transit.So, eventually, US Government will get plain-text for almost everything you ever sent (unless you are a government official, work for well-organized crime syndicate, or you and all your friends are really paranoid).Which means that, eventually, all that mail will get stolen.So, in the best case scenario, a simple relatively benign blackmail-everyone-you-can-to-get-as-much-money-as-possible AI will be able organize a personal WikiLeaks-style breach, for every single person on planet Earth.
No input from nefarious humans interested in exploitingpersonally yourequired.
After all, you are not that interesting, so you have nothing to fear, nothing to hide, and you certainly did not write any still-embarrassing e-mails when you were 16 years old and did not send any nudes of yourself or anyone else to anyone (including any doctors, during the pandemic) ever.It would be glorious, wouldn't it?(Seriously, abstractly speaking, I'm kinda interested in civilization-wide legal and cultural effects ofevery embarrassing, even slightly illegal and/or hypocritical thing every person ever didrelentlessly programmatically exploited as blackmail or worse.
Non-abstractly speaking, why exactly do governments spend public money to make this possible?
After all, hoarding of exploitable material that made a disaster after being stolen worked so well withEternalBlue, and that thing was a fixable bug, which leaked blackmail is not.)That is to say, as a long-term defense measure, this tool is probably useless.
All your mail will get leaked eventually, regardless.
Against random exploitations of your mail serversimaparmsis perfect.Also,imaparmsis a very nice fast mail fetcher, regardless of all of this.Comparison tofetchmailandgetmailimaparms fetchfetches your mail >150 times faster by default (bothfetchmailandgetmailfetch and mark messages one-by-one, incurring huge network latency overheads,imaparms fetchdoes it in (configurable) batches);generates ~150 times less disk writes (imaparms fetch --maildirfsyncs messages to disk in (configurable) batches) improving performance and longevity of your SSD;fetches messages out-of-order to try and maximizemessages/secondmetric when it makes sense (i.e. it temporarily delays fetching of larger messages if many smaller ones can be fetched instead) so that you could efficiently index your mail in parallel with fetching;only does deliveries to a local Maildir (withimaparms fetch --maildiroption) orMDA/LDA(withimaparms fetch --mdaoption, which does the same thing asfetchmail --mdaandgetmail'sMDA_externaloptions), deliveries over SMTP are not and will never be supported (if you want this you can just usemsmtpwithimaparms fetch --mda); thus,imaparmsis much simpler to use when fetching to a localMaildiras it needs no configuration to fetch messages as-is without modifying any headers, thus fetching the same messages twice will produce identical files (which is not true forfetchmail,imaparms fetch --mda MDAis roughly equivalent tofetchmail --softbounce --invisible --norewrite --mda MDA);probably will not work with most broken IMAP servers (fetchmailhas lots of workarounds for server bugs,imaparms fetchdoes not);is written in Python (likegetmail) instead of C (likefetchmail);has other subcommands, not justimaparms fetch.fdmA better explanation of what fdm does.imaparms fetchuses server-side message flags to track state instead of keeping a local database of fetched UIDs;fetches messages out-of-order to try and maximizemessages/secondmetric;generates ~150 times less disk writes;does not do any filtering, offloads that to MDA/LDA;is written in Python instead of C;has other subcommands, not justimaparms fetch.IMAPExpireimaparms deleteallows all UNICODE characters except\nin passwords/passphrases (yes, including spaces, quotes, etc);provides a bunch of options controlling message selection and uses--seenoption by default for destructive actions, so you won't accidentally delete any messages you have not yet fetched even if your fetcher got stuck/crashed;provides GMail-specific options;is written in Python instead of Perl and requires nothing but the basic Python install, no third-party libraries needed;has other subcommands, not justimaparms delete.offlineimap,imapsync, and similarimaparms fetchdoes deliveries from an IMAP server to your Maildir/MDA/LDA instead of trying to synchronize state between some combinations of IMAP servers and localMaildirs (i.e. forimaparms fetchyour IMAP server is always the source, never the destination), which might seem like a lack of a feature at first, butimaparmslacking two-way sync also prevents you from screwing up yourimaparmsinvocation options or restarting the program at an inopportune time and losing all your mail on the server on the next sync as a result (like you can withofflineimap),i.e., withimaparmsyou won't ever lose any messages on the server if you never runimaparms delete, and if you do runimaparms delete,imaparms's defaults try their best to prevent you from deleting any mail you probably did not mean to delete;consequently,imaparmsis much simpler to use as the complexity of its configuration is proportional to the complexity of your usage;imaparms fetchgenerates ~150 times less disk writes;imaparmshas other subcommands, not justimaparms fetch.LicenseGPLv3+.UsageimaparmsA handy Swiss-army-knife-like utility for performing batch operations on messages residing on IMAP servers.
Logins to a specified server, performs specified actions on all messages matching specified criteria in all specified folders, logs out.options:--version: show program's version number and exit-h, --help: show this help message and exit--markdown: show help messages formatted in Markdown-q, --quieter: be less verbosedebugging:--very-dry-run: verbosely describe what the given command line would do and exit--dry-run: perform a trial run without actually performing any changes--debug: dump IMAP conversation to stderrhooks:--notify-success: generate notifications (vianotify-send) describing server-side changes, if any, at the end of each program cycle; most useful if you runimaparmsin background with--everyargument in a graphical environment--success-cmd CMD: shell command to run at the end of each program cycle that performed some changes on the server, i.e. a generalized version of--notify-success; the spawned process will receive the description of the performed changes via stdin; can be specified multiple times--notify-failure: generate notifications (vianotify-send) describing recent failures, if any, at the end of each program cycle; most useful if you runimaparmsin background with--everyargument in a graphical environment--failure-cmd CMD: shell command to run at the end of each program cycle that had some of its command fail, i.e. a generalized version of--notify-failure; the spawned process will receive the description of the failured via stdin; can be specified multiple timesauthentication settings:--auth-allow-login: allow the use of IMAPLOGINcommand (default)--auth-forbid-login: forbid the use of IMAPLOGINcommand, fail if challenge-response authentication is not available--auth-allow-plain: allow passwords to be transmitted over the network in plain-text--auth-forbid-plain: forbid passwords from being transmitted over the network in plain-text, plain-text authentication would still be possible over SSL if--auth-allow-loginis set (default)server connection:
can be specified multiple times--plain: connect via plain-text socket--ssl: connect over SSL socket (default)--starttls: connect via plain-text socket, but then use STARTTLS command--host HOST: IMAP server to connect to (required)--port PORT: port to use (default: 143 for--plainand--starttls, 993 for--ssl)--timeout TIMEOUT: socket timeout, in seconds (default: 60)authentication to the server:
either of--pass-pinentry,--passfile, or--passcmdare required; can be specified multiple times--user USER: username on the server (required)--pass-pinentry: read the password viapinentry--passfile PASSFILE, --pass-file PASSFILE: file containing the password on its first line--passcmd PASSCMD, --pass-cmd PASSCMD: shell command that returns the password as the first line of its stdoutbatching settings:
larger values improve performance but produce longer IMAP command lines (which some servers reject) and cause more stuff to be re-downloaded when networking issues happen--store-number INT: batch at most this many message UIDs in IMAPSTORErequests (default: 150)--fetch-number INT: batch at most this many message UIDs in IMAPFETCHmetadata requests (default: 150)--batch-number INT: batch at most this many message UIDs in IMAPFETCHdata requests; essentially, this controls the largest possible number of messages you will have to re-download if connection to the server gets interrupted (default: 150)--batch-size INT: batchFETCHat most this many bytes of RFC822 messages at once; RFC822 messages larger than this will be fetched one by one (i.e. without batching); essentially, this controls the largest possible number of bytes you will have to re-download if connection to the server gets interrupted whileimaparmsis batching (default: 4194304)polling/daemon options:--every INTERVAL: repeat the command everyINTERVALseconds;imaparmswill do its best to repeat the command precisely everyINTERVALseconds even if the command involesfetching of new messages and--new-mail-cmdinvocations take different time each cycle; if program cycle takes more thanINTERVALseconds orINTERVAL < 60thenimaparmswould sleep for60seconds either way,
this prevents the servers accessed earlier in the cycle from learning about the amount of new data fetched from the servers accessed later in the cycle--every-add-random ADD: sleep a random number of seconds in [0, ADD] range (uniform distribution) before each--everycycle, including the very first one (default: 60);
if you set it large enough to cover the longest single-serverfetch, it will prevent any of the servers learning anything about the data on other servers;
if you runimaparmson a machine that disconnects from the Internet when you go to sleep and you set it large enough, it will help in preventing the servers from collecting data about your sleep cyclemessage search filters:--older-than DAYS: operate on messages older than this many days,the date will be rounded down to the start of the day; actual matching happens on the server, so all times are server time; e.g.--older-than 0means older than the start of today by server time,--older-than 1means older than the start of yesterday, etc; can be specified multiple times, in which case the earliest (the most old) date on the list will be chosen--newer-than DAYS: operate on messages newer than this many days, a negation of--older-than, soeverything from--older-thanapplies; e.g.,--newer-than -1will match files dated into the future,--newer-than 0will match files delivered from the beginning of today, etc; can be specified multiple times, in which case the latest (the least old) date on the list will be chosen--older-than-timestamp-in PATH: operate on messages older than the timestamp (in seconds since UNIX Epoch) recorded on the first line of this PATH, rounded as described above; can be specified multiple times, in which case it will processed as described above--newer-than-timestamp-in PATH: operate on messages newer than the timestamp (in seconds since UNIX Epoch) recorded on the first line of this PATH, rounded as described above; can be specified multiple times, in which case it will processed as described above--older-than-mtime-of PATH: operate on messages older thanmtimeof this PATH, rounded as described above; can be specified multiple times, in which case it will processed as described above--newer-than-mtime-of PATH: operate on messages newer thanmtimeof this PATH, rounded as described above; can be specified multiple times, in which case it will processed as described above--from ADDRESS: operate on messages that have this string as substring of their header's FROM field; can be specified multiple times--not-from ADDRESS: operate on messages that don't have this string as substring of their header's FROM field; can be specified multiple timessubcommands:{list,count,mark,fetch,delete,for-each}list: list all available folders on the server, one per linecount: count how many matching messages each specified folder hasmark: mark matching messages in specified folders in a specified wayfetch: fetch matching messages from specified folders, feed them to an MDA, and then mark them in a specified way if MDA succeedsdelete: delete matching messages from specified foldersfor-each: perform multiple other subcommands, sequentially, on a single server connectionimaparms listLogin, perform IMAPLISTcommand to get all folders, print them one per line.imaparms countLogin, (optionally) perform IMAPLISTcommand to get all folders, perform IMAPSEARCHcommand with specified filters in each folder, print message counts for each folder one per line.options:--porcelain: print in a machine-readable formatfolder search filters:--all-folders: operate on all folders (default)--folder NAME: mail folders to include; can be specified multiple times--not-folder NAME: mail folders to exclude; can be specified multiple timesmessage IMAPSEENflag filters (mutually exclusive):--any-seen: operate on bothSEENand notSEENmessages (default)--seen: operate on messages marked asSEEN--unseen: operate on messages not marked asSEENmessage IMAPFLAGGEDflag filters (mutually exclusive):--any-flagged: operate on bothFLAGGEDand notFLAGGEDmessages (default)--flagged: operate on messages marked asFLAGGED--unflagged: operate on messages not marked asFLAGGEDimaparms markLogin, perform IMAPSEARCHcommand with specified filters for each folder, mark resulting messages in specified way by issuing IMAPSTOREcommands.folder search filters (required):--all-folders: operate on all folders--folder NAME: mail folders to include; can be specified multiple times--not-folder NAME: mail folders to exclude; can be specified multiple timesmessage IMAPSEENflag filters (mutually exclusive, default: depends on other arguments):--any-seen: operate on bothSEENand notSEENmessages--seen: operate on messages marked asSEEN--unseen: operate on messages not marked asSEENmessage IMAPFLAGGEDflag filters (mutually exclusive, default: depends on other arguments):--any-flagged: operate on bothFLAGGEDand notFLAGGEDmessages--flagged: operate on messages marked asFLAGGED--unflagged: operate on messages not marked asFLAGGEDmarking:{seen,unseen,flagged,unflagged}: mark how (required):seen: addSEENflag, sets--unseenif no message flag filter is specifiedunseen: removeSEENflag, sets--seenif no message flag filter is specifiedflag: addFLAGGEDflag, sets--unflaggedif no message flag filter is specifiedunflag: removeFLAGGEDflag, sets--flaggedif no message flag filter is specifiedimaparms fetchLogin, perform IMAPSEARCHcommand with specified filters for each folder, fetch resulting messages in (configurable) batches, feed each batch of messages to an MDA, mark each message for which MDA succeeded in a specified way by issuing IMAPSTOREcommands.folder search filters:--all-folders: operate on all folders (default)--folder NAME: mail folders to include; can be specified multiple times--not-folder NAME: mail folders to exclude; can be specified multiple timesdelivery target (required, mutually exclusive):--maildir DIRECTORY: Maildir to deliver the messages to;
with this specifiedimaparmswill simply drop raw RFC822 messages, one message per file, intoDIRECTORY/new(creating it,DIRECTORY/cur, andDIRECTORY/tmpif any of those do not exists)--mda COMMAND: shell command to use as an MDA to deliver the messages to;
with this specifiedimaparmswill spawnCOMMANDvia the shell and then feed raw RFC822 message into itsstdin, the resulting process is then responsible for delivering the message toMaildir,mbox, etc;maildropfrom Courier Mail Server project is a good KISS defaultdelivery mode (mutually exclusive):--yolo: messages that fail to be delivered into the--maildiror by the--mdaare left un--marked on the server but no other messages get affected, currentimaparms fetchcontinues as if nothing is amiss--careful: messages that fail to be delivered into the--maildiror by the--mdaare left un--marked on the server but no other messages get affected,imaparmsaborts currently runningfetchif zero messages from the current batch get delivered as that usually means that the target file system is out of space, read-only, or generates IO errors (default)--paranoid:imaparmsaborts the process immediately if any of the messages in the current batch fail to be delivered into the--maildiror by the--mda, the whole batch gets left un--marked on the serverhooks:--new-mail-cmd CMD: shell command to run at the end of each program cycle that had new messages successfully delivered into the--maildiror by the--mdaof thisfetchsubcommand; can be specified multiple timesmessage IMAPSEENflag filters (mutually exclusive):--any-seen: operate on bothSEENand notSEENmessages--seen: operate on messages marked asSEEN--unseen: operate on messages not marked asSEEN(default)message IMAPFLAGGEDflag filters (mutually exclusive):--any-flagged: operate on bothFLAGGEDand notFLAGGEDmessages (default)--flagged: operate on messages marked asFLAGGED--unflagged: operate on messages not marked asFLAGGEDmarking:--mark {auto,noop,seen,unseen,flagged,unflagged}: after the message was fetched:auto:seenwhen only--unseenis set (default),flaggedwhen only--unflaggedis set,noopotherwisenoop: do nothingseen: addSEENflagunseen: removeSEENflagflagged: addFLAGGEDflagunflagged: removeFLAGGEDflagimaparms deleteLogin, perform IMAPSEARCHcommand with specified filters for each folder, delete them from the server using a specified method.folder search filters (required):--all-folders: operate on all folders--folder NAME: mail folders to include; can be specified multiple times--not-folder NAME: mail folders to exclude; can be specified multiple timesmessage IMAPSEENflag filters (mutually exclusive):--any-seen: operate on bothSEENand notSEENmessages--seen: operate on messages marked asSEEN(default)--unseen: operate on messages not marked asSEENmessage IMAPFLAGGEDflag filters (mutually exclusive):--any-flagged: operate on bothFLAGGEDand notFLAGGEDmessages (default)--flagged: operate on messages marked asFLAGGED--unflagged: operate on messages not marked asFLAGGEDdeletion method:--method {auto,delete,delete-noexpunge,gmail-trash}: delete messages how:auto:gmail-trashwhen--host imap.gmail.comand the current folder is not[Gmail]/Trash,deleteotherwise (default)delete: mark messages as deleted and then use IMAPEXPUNGEcommand, i.e. this does what you would expect a "delete" command to do, works for most IMAP serversdelete-noexpunge: mark messages as deleted but skip issuing IMAPEXPUNGEcommand hoping the server does as RFC2060 says and auto-EXPUNGEs messages on IMAPCLOSE; this is much faster thandeletebut some servers (like GMail) fail to implement this properlygmail-trash: move messages to[Gmail]/Trashin GMail-specific way instead of trying to delete them immediately (GMail ignores IMAPDeletedflag andEXPUNGEcommand outside of[Gmail]/Trash); you can thenimaparms delete --folder "[Gmail]/Trash"them after (which will default to--method delete), or you could just leave them there and GMail will delete them in 30 daysimaparms for-eachFor each account: login, perform other subcommands given inARGs, logout.This is most useful for performing complex changes--everyonce in while in daemon mode.
Or if you want to set different--folders for different subcommands but run them all at once.Except for the simplest of cases, you must use--beforeARGs so that any options specified inARGs won't be picked up byfor-each.
Run with--very-dry-runto see the interpretation of the given command line.All generated hooks are deduplicated and run after all other subcommands are done.
E.g., if you have severalfetch --new-mail-cmd filter-my-mailas subcommands offor-each, thenfilter-my-mailwill be runonceafter all other subcommands finish.positional arguments:ARG: arguments, these will be split by;and parsed into other subcommandsfolder search filters (will be used as default for subcommands):--all-folders: operate on all folders--folder NAME: mail folders to include; can be specified multiple times--not-folder NAME: mail folders to exclude; can be specified multiple timesNotes on usageWhen specifying account-related settings--userand--pass*options should be always specified last.Internally, new account definition gets emitted when a new--pass*option finishes processing.All server connection and authentication options except--userand--pass*get reused between successively defined accounts, unless overwritten with a new value before the next--pass*option.Message search filters are connected by logical "AND"s so, e.g.,--from "github.com" --not-from "notifications@github.com"will act on messages which have aFrom:header withgithub.combut withoutnotifications@github.comas substrings.fetchsubcommand acts on--unseenmessages by default.deletesubcommand acts on--seenmessages by default.Underfor-each, after any command that produced errors (e.g. afetchthat failed to deliver at least one message because--maildiror--mdafailed to do their job), any successivedeletecommands will be automatically skipped.In theory, in the case of--maildiror--mdafailing to deliver some messagesimaparmsneed not do this as those messages will be left unmarked on the server, but in combination with the default--carefuldelivery option (which see) this behaviour could still be helpful in preventing data loss in the event where the target filesystem starts generating random IO errors (e.g. if you HDD/SSD just failed).In general, this behaviour exists to preventdeletefrom accidentally deleting something important when folder hierarchy on the IMAP server changes to be incompatible with in-useimaparmsoptions. For instance, say you are trying tofetchfrom a folder that was recently renamed and then try todeletefrom--all-folders. The behaviour described above will prevent this from happening.ExamplesList all available IMAP folders and count how many messages they contain:with the password taken frompinentry:imaparms count --host imap.example.com --user account@example.com --pass-pinentrywith the password taken from the first line of the given file:imaparms count --host imap.example.com --user account@example.com \
  --passfile /path/to/file/containing/account@example.com.passwordwith the password taken from the output of password-store utility:imaparms count --host imap.example.com --user account@example.com \
  --passcmd "pass show mail/account@example.com"with two accounts on the same server:imaparms count --porcelain \
  --host imap.example.com \
  --user account@example.com --passcmd "pass show mail/account@example.com" \
  --user another@example.com --passcmd "pass show mail/another@example.com"Now, assuming the following are set:common=(--host imap.example.com --user account@example.com --passcmd "pass show mail/account@example.com")
common_mda=("${{common[@]}}" --mda maildrop)
gmail_common=(--host imap.gmail.com --user account@gmail.com --passcmd "pass show mail/account@gmail.com")
gmail_common_mda=("${{gmail_common[@]}}" --mda maildrop)Count how many messages older than 7 days are in[Gmail]/All Mailfolder:imaparms count "${gmail_common[@]}" --folder "[Gmail]/All Mail" --older-than 7Mark all messages inINBOXas notSEEN, fetch all notSEENmessages marking themSEENas you download them so that if the process gets interrupted you could continue from where you left off:# setup: do once
imaparms mark "${common[@]}" --folder INBOX unseen

# repeatable part
imaparms fetch "${common_mda[@]}" --folder INBOXSimilarly to the above, but useFLAGGEDinstead ofSEEN. This allows to use this in parallel with another instance ofimaparmsusing theSEENflag, e.g. if you want to backup to two different machines independently, or if you want to useimaparmssimultaneously in parallel withfetchmailor other similar tool:# setup: do once
imaparms mark "${common[@]}" --folder INBOX unflagged

# repeatable part
imaparms fetch "${common_mda[@]}" --folder INBOX --any-seen --unflagged

# this will work as if nothing of the above was run
fetchmail

# in this use case you should use both `--seen` and `--flagged` when expiring old messages to only delete messages fetched by both imaparms and fetchmail
imaparms delete "${common[@]}" --folder INBOX --older-than 7 --seen --flaggedSimilarly to the above, but runimaparms fetchas a daemon to download updates every hour:# setup: do once
imaparms mark "${common[@]}" --folder INBOX unseen

# repeatable part
imaparms fetch "${common_mda[@]}" --folder INBOX --every 3600Fetch all messages fromINBOXfolder that were delivered in the last 7 days (the resulting date is rounded down to the start of the day by server time), but don't change any flags:imaparms fetch "${common_mda[@]}" --folder INBOX --any-seen --newer-than 7Fetch all messages fromINBOXfolder that were delivered from the beginning of today (by server time), without changing any flags:imaparms fetch "${common_mda[@]}" --folder INBOX --any-seen --newer-than 0Delete allSEENmessages older than 7 days fromINBOXfolder:Assuming you fetched and backed up all your messages already this allows you to keep as little as possible on the server, so that if your account gets cracked/hacked, you won't be as vulnerable.imaparms delete "${common[@]}" --folder INBOX --older-than 7(--seenis implied by default)DANGEROUS!If you fetched and backed up all your messages already, you can skip--older-thanand just delete allSEENmessages instead:imaparms delete "${common[@]}" --folder INBOXThough, setting at least--older-than 1, to make sure you won't lose any data in case you forgot you are running another instance ofimaparmsor another IMAP client that changes message flags (imaparmswill abort if it notices another client doing it, but better be safe than sorry), is highly recommended anyway.Fetch everything GMail considers to be Spam for local filtering:# setup: do once
mkdir -p ~/Mail/spam/{new,cur,tmp}

cat > ~/.mailfilter-spam << EOF
DEFAULT="\$HOME/Mail/spam"
EOF

imaparms mark "${gmail_common[@]}" --folder "[Gmail]/Spam" unseen

# repeatable part
imaparms fetch "${gmail_common_mda[@]}" --mda "maildrop ~/.mailfilter-spam" --folder "[Gmail]/Spam"Fetch everything from all folders, exceptINBOX,[Gmail]/Starred(because in GMail there are included in[Gmail]/All Mail), and[Gmail]/Trash:imaparms fetch "${gmail_common_mda[@]}" --all-folders \
  --not-folder INBOX --not-folder "[Gmail]/Starred" --not-folder "[Gmail]/Trash"The purpose of this is purely illustrative. In GMail all messages outside of[Gmail]/Trashand[Gmail]/Spamare included in[Gmail]/All Mailso you should probably just fetch that folder instead.GMail-specific deletion mode: move (expire) old messages to[Gmail]/Trashand then delete them:In GMail, deleting messages fromINBOXdoes not actually delete them, nor moves them to trash, just removes them fromINBOXwhile keeping them available from[Gmail]/All Mail.To work around this, this tool provides a GMail-specific--method gmail-trashthat moves messages to[Gmail]/Trashin a GMail-specific way (this is not a repetition, it does require issuing special IMAPSTOREcommands to achieve this):imaparms delete "${gmail_common[@]}" --folder "[Gmail]/All Mail" --older-than 7(--method gmail-trashis implied by--host imap.gmail.comand--foldernot being[Gmail]/Trash,--seenis still implied by default)Messages in[Gmail]/Trashwill be automatically removed by GMail in 30 days, but you can also delete them immediately with:imaparms delete "${gmail_common[@]}" --folder "[Gmail]/Trash" --any-seen --older-than 7(--method deleteis implied by--host imap.gmail.combut--folderbeing[Gmail]/Trash)Every hour, fetch messages from different folders using different MDA settings and then expire messages older than 7 days, all in a single pass (reusing the server connection between subcommands):imaparms for-each "${gmail_common[@]}" --every 3600 -- \
  fetch --folder "[Gmail]/All Mail" --mda maildrop \; \
  fetch --folder "[Gmail]/Spam" --mda "maildrop ~/.mailfilter-spam" \; \
  delete --folder "[Gmail]/All Mail" --folder "[Gmail]/Spam" --folder "[Gmail]/Trash" \
    --older-than 7Note the--and\;tokens, without them the above will fail to parse.Also note thatdeletewill use--method gmail-trashfor[Gmail]/All Mailand[Gmail]/Spamand then use--method deletefor[Gmail]/Trasheven though they are specified together.