2012-07-16 2 views
2

나는 smtpd 모듈을 사용하여 파이썬에서 SMTP 서버를 만들었습니다. 전자 메일을 가져 와서 sqlite 데이터베이스에 저장할 수는 있지만 문제는 검색하는 방법을 모르는 것입니다.python smtp 서버에서 이메일을 가져 오는 방법

다음 코드를 사용해 보았지만 신뢰할 수 있는지 확실하지 않습니다.

import smtpd 
import asyncore 
import sqlite3 
import datetime 
import dol  # custom module that i have created to do authentication while retrieving the email 
import threading 
class CustomSMTPServer(smtpd.SMTPServer): 
def process_message(self, peer, mailfrom, rcpttos, data): 
    print 'Receiving message from:', peer 
    print 'Message addressed from:', mailfrom 
    print 'Message addressed to :', rcpttos 
    print 'Message length  :', len(data) 
    print "Message :",data 
    print data.split("\n\n") 
    smtp_auth_cursor.execute("SELECT username FROM smtp_auth_table") 
    smtp_entry=smtp_auth_cursor.fetchall() 
    print smtp_entry 
    subject="project" 
    for x in smtp_entry: 
     x=x[0] 
     name=x+"@example.com" 
     if x in name: 
      print "entry" 
      d=datetime.date.today() 
      print "entry" 
      date=d.strftime("%A %d. %B %Y") 
      print date 
      time=datetime.datetime.now().strftime("%I:%M %p") 
      print time 
      rcpt=rcpttos[0] 
      try : 
       mail_list_cursor.execute("INSERT INTO mail_list VALUES(101,NULL,?,?,?,?,?,?)",(mailfrom,rcpt,subject,data,date,time)) 
      except sqllite3.Error, e: 
       print "Error %s:" % e.args[0] 
       return 
      print "hasdf" 
      return 
    return 
def __del__(self): 
    server.close() 

def Smtp_service(ip,port): 
    server = CustomSMTPServer(('127.0.0.1', 2035), None) 
    server.set_reuse_addr=True 
    threading.Thread(target=dol.Mail_retrive,args=(ip,port,1)).start() 
    asyncore.loop() 

그러면 I는 이메일을 검색하는 동안 인증이 인증 모듈을 만들었다. 내가 잃어버린 시작 곳 여기입니다 :

class Handler(BaseHTTPRequestHandler): 
''' Main class to present webpages and authentication. ''' 
def do_HEAD(self): 
    print "send header101" 
    self.send_response(200) 
    self.send_header('Content-type', 'text/html') 
    self.end_headers() 

def do_AUTHHEAD(self): 
    print "send header" 
    self.send_response(401) 
    self.send_header('WWW-Authenticate', 'Basic realm=\"Test\"') 
    self.send_header('Content-type', 'text/html') 
    self.end_headers() 

def authenticate(self): 
    conn=sqlite3.connect(smtp_auth_table,isolation_level=None) 
    cursor=conn.cursor() 
    cursor.execute("SELECT MAX(SNO)FROM smtp_auth_table") 
    max_no=cursor.fetchone() 
    cursor.execute("SELECT * FROM smtp_auth_table") 
    entry=cursor.fetchall() 
    passstring=self.headers.getheader('Authorization') 
    flag_no=0 
    for x in entry: 
     setstring='' 
     setstring=x[1]+":"+x[2] 
     setstring=str(setstring) 
     checkstring=base64.b64encode(setstring) 
     checkstring="Basic "+checkstring 
     if checkstring==passstring: 
      return 1 
     flag_no=flag_no+1 
     if flag_no==max_no: 
      return 0 


def do_GET(self): 
    ''' Present frontpage with user authentication. ''' 
    if self.headers.getheader('Authorization') == None: 
     self.do_AUTHHEAD() 
     self.wfile.write('no auth header received') 
     pass 
    elif self.authenticate(): 
     self.do_HEAD() 
     self.wfile.write(self.headers.getheader('Authorization')) 
     self.wfile.write('authenticated!') 
     pass 
    else: 
     self.do_AUTHHEAD() 
     self.wfile.write(self.headers.getheader('Authorization')) 
     self.wfile.write('not authenticated') 
     pass 

httpd = SocketServer.TCPServer(("", 10009), Handler) 

httpd.serve_forever() 

if __name__ == '__main__': 
    main() 

답변

5

SMTP는 메시지를 보낼 수있는 전송 프로토콜입니다 - 엄격하게 배달. 메시지를 검색하는 데 사용할 수 없습니다. 클라이언트 (전자 메일 프로그램)가 메시지를 검색 할 수 있도록 메시지 저장소 위에 POP 또는 IMAP을 구현해야합니다.

그러나 최종 목표가 단순히 웹 페이지에 메시지를 표시하는 것이라면, 파이썬 프레임 워크를 사용하여 메시지 저장소를 읽고 메시지 본문과 헤더를 표시 할 수 있습니다.

가벼운 작업에는 내 즐겨 찾기가 Flask입니다.

+0

팁 부탁드립니다. – TheCreator232

+0

새 메일을 표시하고 사용자가 선택한 메일을 표시하는 것을 목표로하지 않습니다. 사용자가 메일을 삭제할 수도 있습니다. yahoo와 같지만 그 진보는 아닙니다. – TheCreator232

+0

고맙습니다. – TheCreator232