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 = "測試郵件發送地址"<[email protected]>"
addr_to = "測試郵件接收地址"<[email protected]>"
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<
[email protected]>"""
 addr_to = """PythonMail<
[email protected]>"""
 
 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<
[email protected]>"""
    toAddr = """PythonMail<
[email protected]>"""
    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格式郵件


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章