pyhon使用http代理服务器和POP3、SMTP邮件服务器

python标准库已包含对http的支持,通过很简单的办法就可以直接使用http代理服务器获取网页数据:

import httplib
host,port = "192.168.131.54" , "8086" #http proxy server ip and port
conn = httplib.HTTPConnection(host, port)
conn.request(method,url)
print(r.status,r.reason)
print r.read()
python自带的库文件python/lib/poplib.py支持通过pop3接收邮件
该文件末尾自带测试函数,可以直接运行poplib.py:
poplib pop.126.com yourname yourpassword
值得学习的是,在python的库文件中,很多都是自带测试程序,一般在文件末尾,形式如下:
if __name__ == "__main__":
    a = POP3("10.3.4.3","3128")
    print ="this is a test"
这样,直接运行库文件就可以看到测试效果,同时也不干扰正常的import使用。
如果需要通过代理来访问pop,则需要做一点额外的工作,简单起见,直接在poplib.py上面修改,首先复制一份到自己的工作目录,然后修改 class POP3 的 __init__函数:
    def __init__(self, host, port = POP3_PORT):
        self.host = "10.3.4.3"
        self.port = "3128"
        msg = "getaddrinfo returns an empty list"
        self.sock = None
         
        for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM):
            af, socktype, proto, canonname, sa = res
            try:
                self.sock = socket.socket(af, socktype, proto)
                self.sock.connect(sa)
            except socket.error, msg:
                if self.sock:
                    self.sock.close()
                self.sock = None
                continue
            break
        if not self.sock:
            raise socket.error, msg
        self.file = self.sock.makefile('rb')
        self._debugging = 0
        self._putline("CONNECT 220.181.15.121:110 HTTP/1.0/r/n")  #pop.126.com的ip地址
        msg_proxy = self._getline()
        msg_proxy = self._getline()
        self.welcome = self._getresp()
简单起见,上面的代理服务器和pop服务器的ip地址是直接添上去的,实际使用用时需要适当修改成方便应用的形式。
 
python通过smtp认证服务器发邮件的操作也是相当简单:
(如需要支持中文,注意指明编码,并保持所有编码一致)
 
# -*- coding: GB2312 -*-
import smtplib

addr_from = "测试邮件发送地址"< mymail@gmail.com >"
addr_to = "测试邮件接收地址"< mymail@gmail.com >"
smtp = "smtp.gamil.com"
head_format = """To: %s/nFrom: %s/nContent-Type: text/plain;/ncharset="gb2312"/nSubject: Test mail from python/n/n"""
body = "This is a test mail./nSecond line./n3rd line."

server = smtplib.SMTP('smtp.changhong.com')
server.login("name","password")
head = head_format%(addr_to,self.addr_from)
msg = head + body
server.sendmail(self.addr_from,addr_to ,msg)
server.quit()
另外如果需要发送html格式的邮件则又要额外多费一点功夫了,一下是一个简单的发送html格式邮件的py文件,我已经把编码固定成了GB2312:
# -*- coding: GB2312 -*-
class smtp_server:
 server = None
 subject = "Python mail sender"
 addr_from = """PythonMail<
abc@126.com >"""
 addr_to = """PythonMail<
abc@126.com >"""
 
 charset = 'GB2312'
 
 def __init__(self):
  import smtplib
  self.server = smtplib.SMTP("smtp.126.com")
  self.server.login("user_name","mypass")
  return
 
 def __del__(self):
  if(self.server != ""):
   self.server.quit()
  return  
    
 def send(self, addr_from , addr_to ,msg):
  self.server.sendmail(addr_from , addr_to , msg)
  return
 
 def send_html(self, addr_from , addr_to ,html , subject):
  msg = self.create_html_mail(html,None,subject,addr_from,addr_to)
  self.send(addr_from,addr_to,msg)
  return
 
 def create_html_mail(self,html, text=None ,subject=None, addr_from=None , addr_to=None):
    
  "Create a mime-message that will render as HTML or text, as appropriate"
  import MimeWriter
  import mimetools
  import cStringIO
  import base64
  
  charset = self.charset
  if subject is None:
   subject=self.subject
  if addr_from is None:
   addr_from=self.addr_from
  if addr_to is None:
   addr_to=self.addr_to  
  
  if text is None:
   # Produce an approximate textual rendering of the HTML string,
   # unless you have been given a better version as an argument
   import htmllib, formatter
   textout = cStringIO.StringIO(  )
   formtext = formatter.AbstractFormatter(formatter.DumbWriter(textout))
   parser = htmllib.HTMLParser(formtext)
   parser.feed(html)
   parser.close(  )
   text = textout.getvalue(  )
   del textout, formtext, parser
  
  out = cStringIO.StringIO(  ) # output buffer for our message
  htmlin = cStringIO.StringIO(html)
  txtin = cStringIO.StringIO(text)
  
  writer = MimeWriter.MimeWriter(out)
  
  # Set up some basic headers. Place subject here
  # because smtplib.sendmail expects it to be in the
  # message body, as relevant RFCs prescribe.
  writer.addheader("From",addr_from)
  writer.addheader("To",addr_to)
  writer.addheader("Subject", subject)
  writer.addheader("MIME-Version", "1.0")
  
  # Start the multipart section of the message.
  # Multipart/alternative seems to work better
  # on some MUAs than multipart/mixed.
  writer.startmultipartbody("alternative")
  writer.flushheaders(  )
  
  # the plain-text section: just copied through, assuming iso-8859-1
  subpart = writer.nextpart(  )
  pout = subpart.startbody("text/plain", [("charset", charset)])
  pout.write(txtin.read(  ))
  txtin.close(  )
  
  # the HTML subpart of the message: quoted-printable, just in case
  subpart = writer.nextpart(  )
  subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
  pout = subpart.startbody("text/html", [("charset", charset)])
  mimetools.encode(htmlin, pout, 'quoted-printable')
  htmlin.close(  )
  
  # You're done; close your writer and return the message body
  writer.lastpart(  )
  msg = out.getvalue(  )
  out.close(  )
  return msg
if __name__=="__main__":
    f = open("test.html", 'r')
    html = f.read(  )
    f.close(  )
    fromAddr = """PythonMail<
abc@126.com >"""
    toAddr = """PythonMail<
abc@126.com >"""
    server = smtp_server()
    #message = server.create_html_mail(html)
    #server.send(fromAddr, toAddr, message)
    server.send_html(fromAddr, toAddr,html,"subject")

相应修改smtp服务器的地址和认证信息,保存为"html_smtp.py"文件,直接运行即可发送内容为当前目录下名为:“test.html”的html格式邮件

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2011-01-19 14:56  邵珠庆  阅读(1182)  评论(0编辑  收藏  举报