python使用代理进行邮件发送

2020年4月21日 评论 223 views 1148字阅读3分49秒
import sys,os
import smtplib, httplib, socket

 class SMTP(smtplib.SMTP, httplib.HTTPConnection):
    def connect(self, host='localhost', port = 0, proxy=None):
        if proxy is None:
            return smtplib.SMTP.connect(self, host, port)
        else:
            if not port and (host.find(':') == host.rfind(':')):
                i = host.rfind(':')
                if i >= 0:
                    host, port = host[:i], host[i+1:]
                    try: port = int(port)
                    except ValueError:
                        raise socket.error, "nonnumeric port"
            if not port:
                port = self.default_port

            if self.debuglevel > 0:
            print >>sys.stderr, 'connect:', (host, port)

            proxy_host, proxy_port = proxy
            conn = httplib.HTTPConnection(proxy_host, proxy_port)
            conn.connect()
            conn.send("CONNECT %s:%d HTTP/1.0\r\n\r\n" % (host, port))
            response = conn.response_class(conn.sock, strict=conn.strict,
method=conn._method)
            (version, code, message) = response._read_status()
            if code != 200:
                conn.close()
                raise socket.error, "Proxy connection failed: %d %s" %
(code, message.strip())
            while True:
                line = response.fp.readline()
                if line == '\r\n':
                    break
            self.sock = conn.sock
            (code, msg) = self.getreply()
            if self.debuglevel > 0:
                print >>sys.stderr, "connect:", msg
            return (code, msg)

 if __name__ == '__main__':
    smtp = SMTP()
    smtp.debuglevel = 1
    smtp.connect('smtp.qq.com', 25, proxy=('127.0.0.1', 8123))
    smtp.login('1234...@qq.com', '12345678')
    smtp.close()
weinxin
公众号
在号内与我交流,回复【资源】获取技术大礼包
Python最后更新:2020-8-31
小熊