IMAP/SMTP via HTTPS Proxy

In some places internet access is provided via proxy. Some proxies block imap and smtp and allow only ports 80 and 443. If your email client doesn’t have proxy configuration (like my beloved Mutt), then you need to forward imap and smtp by hand. If the proxy you are behind supports https this means you can bypass it via https connect method.

To demonstrate that I’ll install Proxytunnel on my Ubuntu 14.04. After that I am creating 2 upstart scripts that launch proxy-tunnel daemons from proxy to imap/smtp (in this example to gmail’s servers). The daemons are started on system’s boot and are listening for imap connections on localhost:993 and smtp on localhost:993. For simplicity I’m adding my mail servers to hosts file, without that I would need to reconfigure my mail client to use localhost instead of *.gmail.com.

sudo apt-get install proxytunnel
sudo touch /etc/init/tunnel-imap.conf /etc/init/tunnel-smtp.conf
sudo chmod 644 /etc/init/tunnel-imap.conf /etc/init/tunnel-smtp.conf

/etc/init/tunnel-imap.conf:

# proxy daemon for Gmail

description     "proxy daemon for Gmail imap"

start on runlevel [2345]

expect fork
respawn
respawn limit 10 5

exec    /usr/bin/proxytunnel -p proxy.com:80 -d imap.gmail.com:993 -a 993

/etc/init/tunnel-smtp.conf:

# proxy daemon for Gmail

description     "proxy daemon for Gmail smtp"

start on runlevel [2345]

expect fork
respawn
respawn limit 10 5

exec    /usr/bin/proxytunnel -p proxy.com:80 -d smtp.gmail.com:587 -a 587

add to /etc/hosts:

127.0.1.1   imap.gmail.com
127.0.1.1   smtp.gmail.com

Reboot

Tip 1: if you are an Upstart guru, you can make 1 upstart script instead of 2 🙂
Tip 2: one can use iptables instead of hosts

# iptables -t nat -A OUTPUT -d smtp.gmail.com -j DNAT --to-destination 127.0.1.1

Tip 3: there is a Python script that does the same job (didn’t test it)