Python smtplib proxy support

Sinista picture Sinista · Mar 9, 2011 · Viewed 20.7k times · Source

I would like to send email through a proxy.

My current implementation is as follows:

I connect to the smtp server with authentication. After I've successfully logged in, I send an email. It works fine but when I look at the email header I can see my host name. I would like to tunnel it through a proxy instead.

Any help will be highly appreciated.

Answer

aivarsk picture aivarsk · Sep 26, 2014

Use SocksiPy:

import smtplib
import socks

#'proxy_port' should be an integer
#'PROXY_TYPE_SOCKS4' can be replaced to HTTP or PROXY_TYPE_SOCKS5
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS4, proxy_host, proxy_port)
socks.wrapmodule(smtplib)

smtp = smtplib.SMTP()
...