Skip to content

Instantly share code, notes, and snippets.

@cympfh cympfh/check_gmail.coffee
Last active Feb 6, 2016

Embed
What would you like to do?
connect GMail with openssl and type IMAP commands in CoffeeScript
#!/usr/bin/env coffee
{execSync, spawn} = require 'child_process'
client = spawn 'openssl', ("s_client -crlf -connect imap.gmail.com:993".split ' ')
gmail = 'your@gmail.com'
password = 'Your_Strong$Password'
decode = (s) ->
execSync "echo #{s} | base64 -d | nkf"
fs = require 'fs'
num = -1 # num of inbox mails
if fs.existsSync ".#{gmail}"
num = (fs.readFileSync ".#{gmail}", 'utf-8') | 0
overwrite = (num) ->
fs.writeFileSync ".#{gmail}", num
# implement as you like
notify = (from, subject) ->
msg = "To: #{gmail}\n#{from}\n#{subject}"
console.log msg
suicide = ->
client.kill 'SIGHUP'
client.stdout.on 'data', (data) ->
data = data.toString()
switch
when (data.indexOf 'OK Gimap ready') >= 0
client.stdin.write "? login #{gmail} #{password}\n"
when (data.indexOf 'authenticated (Success)') >= 0
client.stdin.write '? select inbox\n'
when (/\*\s\d*\sEXISTS/.test(data))
m = data.match(/\*\s(\d*)\sEXISTS/)[1] | 0
if m > num
client.stdin.write "? fetch #{m} body[]\n"
overwrite m
else
suicide()
when (data.indexOf 'Message-ID: ') >= 0
lines = data.split '\n'
from = false
subject = false
for line in lines
line = line.replace /=\?UTF-8\?B\?(.*)\?=/g, (a, b) -> decode(b)
line = line.replace /=\?ISO-2022-JP\?B\?(.*)\?=/g, (a, b) -> decode(b)
line = line.replace /=\?iso-2022-jp\?B\?(.*)\?=/g, (a, b) -> decode(b)
line = line.replace /=\?Shift_JIS\?B\?(.*)\?=/g, (a, b) -> decode(b)
if (not from) and /^From:/.test(line)
from = line
if (not subject) and /^Subject:/.test(line)
subject = line
notify from, subject
suicide()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.