Skip to content

Instantly share code, notes, and snippets.

@niclashoyer
Last active December 20, 2015 21:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niclashoyer/6196937 to your computer and use it in GitHub Desktop.
Save niclashoyer/6196937 to your computer and use it in GitHub Desktop.
IMAP mail retriever written in CoffeeScript to forward mail to another process.

echoimap

Create a settings file ~/.echoimap.json with the following content:

{
	"imap": {
		"host": "imap.example.com",
		"user": "imapuser",
		"password": "imappassword",
		"port": 993,
		"tls": true,
		"tlsOptions": {
			"rejectUnauthorized": false
		}
	},
	"exec": {
		"command": "tee",
		"args": ["mail.log"]
	}
	"clean": {
		"after": {
			"days": 7
		},
		"interval": 300000
	}
}

and start receiving mails instantly

git clone https://gist.github.com/6196937.git
cd 6196937
npm install imap moment
npm install -g forever coffee-script
coffee -c echoimap.coffee
forever start -m 5 echoimap.js
fs = require 'fs'
Imap = require 'imap'
{spawn} = require 'child_process'
moment = require 'moment'
home = process.env['HOME']
conf = JSON.parse fs.readFileSync home + '/.echoimap.json'
imapdate = (date) ->
m = moment date
m.format ''
imap = new Imap conf.imap
cleanOldMails = ->
date = moment().subtract(conf.clean.after).format 'DD-MMM-YYYY'
imap.search [ [ 'BEFORE', date ], 'SEEN', 'UNDELETED' ], (err, results) ->
if err
console.error err
else if results.length > 0
imap.addFlags results, 'DELETED', (err) ->
if err?
console.error err
else
imap.expunge (err) ->
if err?
console.error err
imap.on 'ready', ->
imap.openBox 'INBOX', (err, box) ->
if err?
console.error err
process.exit 1
console.log 'connected to ' + conf.imap.host
if conf.clean?.after?
if conf.clean.interval is undefined
conf.clean.interval = 300000 # 5min
setInterval cleanOldMails, conf.clean.interval
do cleanOldMails
imap.on 'mail', ->
imap.search [ 'UNSEEN' ], (err, results) ->
if err?
console.error err
return
if results.length is 0
return
f = imap.fetch results,
bodies: ''
markSeen: true
f.on 'message', (msg) ->
msg.on 'body', (stream, info) ->
if conf.exec.command?
child = spawn conf.exec.command, conf.exec.args,
stdio: [
'pipe', 'pipe', process.stderr
]
child.on 'error', (err) ->
console.error err
stream.pipe child.stdin
imap.on 'error', (err) ->
console.error err
imap.on 'end', ->
console.log 'disconnected'
process.exit 1
imap.connect()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment