Using IMAPFilter to Process Emails
To keep IMAP passwords hidden, we want to encrypt them with GPG. Since the filtering will run on it’s own without any human interaction, the GPG keys can’t have a password.
This also means IMAPFilter should be running on a secure machine that no one else can access easily.
Assuming you have GPG keys without a password, install pass and imapfilter.
sudo apt-get install pass imapfilterIntialize pass:
pass initi your-gpg-id@foobar.comOr if you’d rather use your GPG key id:
gpg --list-keys --keyid-format LONGLook for a line that looks like “pub rsa3072/XXXXXXXXXXXXXXXX”. The XXXXXXXXXXXXXXXX is your key ID and then:
pass init XXXXXXXXXXXXXXXXNow let’s save the password to the IMAP account.
pass insert Email/acccount1Create a file called config.lua in a .imapfilter directory and enter the following as a template:
-- Get password from pass program
function get_password(account)
local handle = io.popen('pass Email/' .. account)
local result = handle:read("*a")
handle:close()
return result:gsub("^%s*(.-)%s*$", "%1") -- Trim whitespace
end
-- Function to safely create folders if they don't exist
function ensure_folder(account, folder)
if not account[folder] then
account:create_folder(folder)
end
end
-- Account information
my_email_account = IMAP {
server = '<ENTER IMAP SERVER>',
username = '<EMAIL USERNAME>',
password = get_password('account1'),
ssl = 'auto'
}
ensure_folder(my_email_account, 'Archive')
ensure_folder(my_email_account, 'Later')
-- Get messages from INBOX
my_inbox = my_email_account.INBOX:select_all()
-- Filter messages
my_inbox:contain_from('subscribers@hellworld.com'):move_messages(my_email_account['Archive'])
my_inbox:contain_from('John Smith'):move_messages(my_email_account['Later'])
Create a script called ‘run_filter.sh’ to run IMAPFilter with this configuration:
#!/usr/bin/bash
/usr/bin/imapfilter -c /home/ubuntu/.imapfilter/config.luaMake the script executable:
chmod +x run_filter.shTest by running ./run_filter.sh.
If it works, create a cron entry for run_filter.sh