Newer
Older
Import / projects / LGN-IP3870 / t / orig / ipemailmanager.py
import time, ntptime
import config
import os , os.path
import utils
import runtime
from roxiadebug import *
from setting import setting
import StringIO
import sgmllib
import socket, evas
import tempfile

class StorageFullError(Exception):
	pass

class FoundBody(Exception):
	pass

class ExtractBody(sgmllib.SGMLParser):
	def __init__(self, verbose=0):
		sgmllib.SGMLParser.__init__(self, verbose)
		self.data = ''
		self.isp = False

	def handle_data(self, data):
		if self.data is not None:
			if self.isp:
				self.data += data

	def start_body(self, attrs):
		self.data = ''

	def end_body(self):
		self.data = self.data[:-1]
		raise FoundBody

	def start_p(self, attrs):
		self.isp = True

	def end_p(self):
		self.isp = False
		self.data += '\n'
# RCH / [20060817_1]
class ExtractBody2(sgmllib.SGMLParser):
	def __init__(self, verbose=0):
		sgmllib.SGMLParser.__init__(self, verbose)
		self.data = ''
		self.flag = True

	def start_style(self, attrs):
		self.flag = False

	def end_style(self):
		self.flag = True

	def handle_data(self, data):
		data2 = data.split()
		data3 = ''.join(data2)

		if len(data3) > 0:
			if self.flag is True:
				self.data += data
				self.data += '\n'

def html_to_text2(htmlStr):
	par = ExtractBody2()
	par.feed(htmlStr)
	par.close()
	return par.data		
# RCH / [20060817_1]--

def html_to_text(htmlStr):
	if config.ipemail_debug:
		print '## html_to_text ##'
	par = ExtractBody()
	try:
		par.feed(htmlStr)
		par.close()
	except FoundBody:
		return par.data
	return htmlStr

def compose_address(addr_list):
	addr_str = ''
	tmpList = []
	if not addr_list:
		return addr_str
	if str == type(addr_list):
		tmpList.append(addr_list)
		addr_list = tmpList
	if list != type(addr_list):
		return addr_list

	for i in addr_list:
		addr_str += i
		addr_str += '\0'
	return addr_str

def decompose_address(addr_str):
	if str != type(addr_str):
		return addr_str

	idx = addr_str.find('\n')
	if -1 != idx:
		addr_str = addr_str[0:idx]
	addr_list = []
	index = 0
	while index < len(addr_str):
		endaddr = addr_str[index:].find('\0')
		if -1 == endaddr:
			addr_list.append(addr_str[index:])
			break
		addr_list.append(addr_str[index:index+endaddr])
		index += (endaddr+1)

	return addr_list

#inbox일 경우 idx값은?
def list_get(list, f):
	for l in list:
		#if l[1] == f:
		if l[0] == f:
			return l

	return None

def list_get_inbox(list, f):
	for l in list:
		if config.ipemail_debug: print l
		if l[1] == f:
			return l
	return None

class IpEmailManagerBase:
	read_path = ''
	read_info_path = ''
	personal_path = ''
	personal_info_path = ''
	sent_path = ''
	sent_info_path = ''
	draft_path = ''
	draft_info_path = ''

	def __init__(self):
		if self.read_path: utils.make_dir(self.read_path)
		if self.personal_path: utils.make_dir(self.personal_path)
		if self.sent_path: utils.make_dir(self.sent_path)
		if self.draft_path: utils.make_dir(self.draft_path)

		self.read_info = []#local
		self.header_info = []#server
		self.received_info = []#local+server
		self.personal_info = []
		self.sent_info = []
		self.draft_info = []

	#Roxia Begin spree 06.08.23
	def delete_notcomplete(self):
		deletefname = ''
		if self.read_info:
			flist = os.listdir(self.read_path)
			if config.ipemail_debug: print 'flist', flist, '\n\n\n'
			for fname in flist:
				deletefname = self.read_path+fname
				if config.ipemail_debug: print 'fname', fname
				if config.ipemail_debug: print deletefname
				if -1 != deletefname.find('Attach'):
					continue
					
				if not list_get_inbox(self.read_info, deletefname):
					if config.ipemail_debug: print 'delete', deletefname
					utils.remove_file(deletefname)
					utils.remove_dir(deletefname+'Attach/')
					if os.path.exists(deletefname+'Attach/'):
						os.rmdir(deletefname+'Attach/')
					if config.ipemail_debug: print '==========delete=========='
		else:
			self.remove_all_received()
	#Roxia End spree

	def replaceMonth(self,str2):
		months = ['Jan', 'Feb', 'Mar' ,'Apr','May','Jun','Jul','Aug','Sep', 'Oct','Nov', 'Dec']
		i= 0
		str1 = ''
		for k in months:
			i +=1
			if str2.find(k) > -1:
				str1 = str2.replace(k,'%02d' % i)
				break
		return str1

	def get_header_info(self):
		return self.header_info

	def set_header_info(self, header_info):
		self.header_info = header_info

	def set_personal_info(self, personal_info):
		self.personal_info = personal_info

	def extract_address(self,addr):

		if not addr:
			return
		try:
			if addr.find('<') > -1:
				add0 = addr[addr.find('<')+1:addr.rfind('>')]
			else:
				add0 = addr
			if config.ipemail_debug: print 'extract_address:',addr,'==>',add0
		except AttributeError:
			add0 = addr
		return add0

	def mail_log_out(self):
		if config.ipemail_debug: print 'mail_log_out execute...'
		try:
			if setting.email_protocol == 'POP':
				runtime.mbox.quit()
			else:
				runtime.mbox.close()
				runtime.mbox.logout()
		except AttributeError:
			pass
		runtime.mbox = None

	def mail_log_in(self):
		ret = 0
		if setting.email_protocol == 'POP':
			import poplib
			try:
				if config.ipemail_debug: print('acessing pop3 mail server',setting.email_popserver)
				runtime.mbox = poplib.POP3(setting.email_popserver)
				if config.ipemail_debug: print('authentificating user..',setting.email_userid)
				runtime.mbox.user(setting.email_userid)
				if config.ipemail_debug: print('authentificating password..',setting.email_password)
				runtime.mbox.pass_(setting.email_password)
				ret = 1
			except poplib.error_proto:#-ERR Not matched password
				if config.ipemail_debug: print poplib.error_proto
				ret = 0
			except socket.gaierror:#(-2,'Name or service not known') #can't find mail server
				if config.ipemail_debug: print socket.gaierror
				ret = -2
			#socket.gaierror: (-3, 'unknown error.')
			except socket.error:#(111,'Connection  refused')
				if config.ipemail_debug: print socket.error
				ret = 111
		else:
			import imaplib
			try:
				if config.ipemail_debug: print('acessing imap4 mail server',setting.email_imapserver)
				runtime.mbox = imaplib.IMAP4(setting.email_imapserver)
				if config.ipemail_debug: print('logining user..',setting.email_userid,' setting.email_password:',setting.email_password)
				# RHC / [20060913_1]
				# 현재는 LOGIN과 CRAM-MD5만 지원함.
				#runtime.mbox.login(setting.email_userid,setting.email_password)
				capaChallenge = runtime.mbox.capabilities
				authFlag = False
				for capa in capaChallenge:
					authIndex = capa.find('AUTH=')
					if authIndex != -1:
						imapAuth = capa[authIndex+5:]
						if imapAuth == 'CRAM-MD5':
							authFlag = True
							break

				if authFlag is True:
					runtime.mbox.login_cram_md5(setting.email_userid,setting.email_password)
				else:
					runtime.mbox.login(setting.email_userid,setting.email_password)
				# RHC / [20060913_1]--				
				runtime.mbox.select('INBOX')
				ret = 1
			# RHC / [20060810_1]
			# TdE waring 55
			#except imaplib.error:#LOGIN failure .wrong passwd
			except imaplib.IMAP4.error:#LOGIN failure .wrong passwd
			# RHC / [20060810_1]--
				# RHC / [20060913_2]
				#if config.ipemail_debug: print imaplib.error
				if config.ipemail_debug: print imaplib.IMAP4.error
				# RHC / [20060913_2]--
				ret = 111
			except socket.gaierror:#(-2,'Name or service not known') #can't find mail server
				if config.ipemail_debug: print socket.gaierror
				ret = -2
			#socket.gaierror: (-3, 'unknown error.')
			except socket.error:#(111,'Connection  refused')
				if config.ipemail_debug: print socket.error
				ret = 111
		return ret

	# RHC / [20060901_1]
	def checkEmptyBox(self, box = 1):
		if box == 1:
			mailbox_path = self.read_path
		elif box == 2:
			mailbox_path = self.personal_path
		elif box == 3:
			mailbox_path = self.sent_path
		elif box == 4:
			mailbox_path = self.draft_path

		flist = os.listdir(mailbox_path)

		if len(flist) > 0:
			return False
		else:
			return True
	# RHC / [20060901_1]--

	def reload(self, box = 1):# 1:inbox 2:outbox 3:sent 4:draft
		self.header_info = []
		mailbox_path = ''
		info = []
		binbox = True
		#변수만 달라지고 참조값은 같다.
		if box == 1:
			mailbox_path = self.read_path
			info = self.read_info = []
			binbox = False
		elif box == 2:
			mailbox_path = self.personal_path
			info = self.personal_info = []
		elif box == 3:
			mailbox_path = self.sent_path
			info = self.sent_info = []
		elif box == 4:
			mailbox_path = self.draft_path
			info = self.draft_info = []

		filename = ''
		addr = []
		fromAddress = []
		toAddress = []
		cc = []
		bcc = []
		subject = ''
		date = ''
		# RHC / [20061127_3]
		attaches = []
		# RHC / [20061127_3]--
		read = ''
		sent = ''
		body = ''

		content_type = ''

		#실제 디렉토리의 message 000000xxx파일을 읽어서 info정보에 저장한다.
		flist = os.listdir(mailbox_path)
		index1 = 0
		for fname in flist:
			if os.path.isfile(mailbox_path + fname):
				try:
					idx = 0

					fp = open(mailbox_path + fname, 'r')
					for line in fp.xreadlines():#filename, fromAddress, cc,bcc,subject, date, attach, read,sent,body순
						line = line.strip()
						if idx == 0:
							filename = line
						elif idx == 1:
							if binbox:
								addr = fromAddress = decompose_address(line)
							else:
								addr = toAddress = decompose_address(line)
						elif idx == 2:
							cc = decompose_address(line)
						elif idx == 3:
							bcc = decompose_address(line)
						elif idx == 4:
							subject = line
						elif idx == 5:
							date = line
						elif idx == 6:
							attaches = decompose_address(line)
							if not attaches:
								attaches = []
						elif idx == 7:
							read = int(line)
						elif idx == 8:
							bsent = 1
							if 0 == int(line):
								bsent = 0
							sent = bsent
						elif idx == 9:
							content_type = line
						elif idx == 10: body = line
						elif idx > 10: body += line
						idx +=1


					index1 += 1
					# RHC / [20060807_2]
					# attach icon을 제공하기 위한 수정 중 오류 수정.
					if box == 1:#inbox
						info.append(['I' + str(index1), filename, addr, cc, bcc, \
 							subject, date, attaches, read, sent, content_type, body])
					else:
						info.append([filename, addr, cc, bcc, subject, date, attaches, \
							read, sent, content_type, body])
					# RHC / [20060807_2]--
					fp.close()

				except IOError:
					if config.ipemail_debug: print( '**************ipmanager.reload().ioerror ',box,'*************')

		if config.ipemail_debug: print( '**************ipmanager ',box,' reload()*************')
		return info

	#0 = received, 1 = personal(out), 2 = sent, 3 = draft
	def save_infos(self, boxtype=0):
		if 0 == boxtype:
			info = self.read_info
			path = self.read_path
		elif 1 == boxtype:
			info = self.personal_info
			path = self.personal_path
		elif 2 == boxtype:
			info = self.sent_info
			path = self.sent_path
		elif 3 == boxtype:
			info = self.draft_info
			path = self.draft_path
		if 0 == boxtype:
			if config.ipemail_debug: print('save_infos.read_info_path:',self.read_info_path)
			if config.ipemail_debug: print 'saving read.info'
			f = open(self.read_info_path, 'w')
			for data in self.read_info:
				index, filename, fromAddress, cc, bcc, subject, date, attach, \
					read, sent, content_type, body = data
				if not date:
					y, m1, d, h, m2, s = time.localtime(ntptime.ntime())[:6]
					date = '%d %02d %02d %02d %02d %d %d' % (y, m1, d, h, m2, s, 0)
				from_str = compose_address(fromAddress)
				cc_str = compose_address(cc)
				bcc_str = compose_address(bcc)
				attach_str = compose_address(attach)
				f.write('%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n' % \
				(filename, from_str, cc_str, bcc_str, subject, date, \
					attach_str, read, sent, content_type, body))
			f.close()
		elif 1 == boxtype:
			if config.ipemail_debug: print 'save outbox'
			f = open(self.personal_info_path, 'w')
			for data in self.personal_info:
				if config.ipemail_debug: print('save_infos.personal_info.data:',data)
				filename, toAddress, cc, bcc, subject, date, attach, \
					read, sent, content_type, body = data
				if not date:
					y, m1, d, h, m2, s = time.localtime(ntptime.ntime())[:6]
					date = '%d %02d %02d %02d %02d %d %d' % (y, m1, d, h, m2, s, 0)
				to_str = compose_address(toAddress)
				cc_str = compose_address(cc)
				bcc_str = compose_address(bcc)
				attach_str = compose_address(attach)
				f.write('%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n' % \
				(filename, to_str, cc_str, bcc_str, subject, date, \
					attach_str, read, sent, content_type, body))
			f.close()
		elif 2 == boxtype:
			if config.ipemail_debug: print 'save sent'
			f = open(self.sent_info_path, 'w')
			for data in self.sent_info:
				if config.ipemail_debug: print('save_infos.sent_info.data:',data)
				filename, toAddress, cc, bcc, subject, date, attach, \
					read, sent, content_type, body = data
				if not date:
					y, m1, d, h, m2, s = time.localtime(ntptime.ntime())[:6]
					date = '%d %02d %02d %02d %02d %d %d' % (y, m1, d, h, m2, s, 0)
				to_str = compose_address(toAddress)
				cc_str = compose_address(cc)
				bcc_str = compose_address(bcc)
				attach_str = compose_address(attach)
				f.write('%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n' % \
				(filename, to_str, cc_str, bcc_str, subject, date, \
					attach_str, read, sent, content_type, body))
			f.close()
		elif 3 == boxtype:
			if config.ipemail_debug: print 'save draft'
			f = open(self.draft_info_path, 'w')
			for data in self.draft_info:
				if config.ipemail_debug: print('save_infos.draft_info.data:',data)
				filename, toAddress, cc, bcc, subject, date, attach, \
					read, sent, content_type, body = data
				if not date:
					y, m1, d, h, m2, s = time.localtime(ntptime.ntime())[:6]
					date = '%d %02d %02d %02d %02d %d %d' % (y, m1, d, h, m2, s, 0)
				to_str = compose_address(toAddress)
				cc_str = compose_address(cc)
				bcc_str = compose_address(bcc)
				attach_str = compose_address(attach)
				if config.ipemail_debug: print '==', (filename, to_str, cc_str, bcc_str, subject, date, attach_str, read, sent,body)
				f.write('%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n' % \
				(filename, to_str, cc_str, bcc_str, subject, date, \
					attach_str, read, sent, content_type, body))
			f.close()

	#mail header receive

	#Roxia Begin cmlim 06.06.10
	"""
	def receive_header(self):
		import email
		if setting.email_protocol == 'POP':
			import poplib
		else:
			import imaplib
		self.header_info = []
		if config.ipemail_debug: print('receive message headers...')
		self.readFlag = 0

		if setting.email_protocol == 'POP':
			noMsg, tsize = runtime.mbox.stat()

			for k in range(1, noMsg+1):
				res = runtime.mbox.top(k, 0)[1]

				headerMsg = '\n'.join(res)
				msg = email.message_from_string(headerMsg)
				toAddress = msg['to']
				fromAddress = msg['from']
				cc = msg['cc']
				bcc = msg['bcc']
				#Roxia Begin cmlim 06.04.06
				#subject = msg['subject']
				from ietp import decodeHeader
				subject = decodeHeader(msg['subject'])
				#Roxia End cmlim 06.04.06
				date1 = msg['date']
				if config.ipemail_debug: print date1
				if not date1:
					y, m1, d, h, m2, s = time.localtime(ntptime.ntime())[:6]
					date1 = '%d %02d %02d %02d %02d %d %d' % (y, m1, d, h, m2, s, 0)
					if config.ipemail_debug: print('IpEmailListStage no date exist:',date1)
				else:
					tmp = date1[date1.rfind(',')+1:date1.rfind(':')+3]
					tmp = self.replaceMonth(tmp.strip())
					try:
						date1 =  time.strptime(tmp,'%d %m %Y %H:%M:%S')
						date1 = '%s %02d %02d %02d %02d %s %s' % date1[:7]
					except ValueError:#spam
						y, m1, d, h, m2, s = time.localtime(ntptime.ntime())[:6]
						date1 = '%d %02d %02d %02d %02d %d %d' % (y, m1, d, h, m2, s, 0)
				if msg.get_content_type().startswith('multipart'):
					attach = ['0']#아무값으로 초기화.
				else:
					attach = []
				read = 0#pop이면..무조건.
				sent = 0
				self.header_info.append((k, '', fromAddress, cc, bcc, subject, \
					date1, attach, read, sent, '', None))
		else:
			resp,items1 = runtime.mbox.search(None, 'ALL')
			#차례대로 아이템 붙이기
			import string,rfc822
			no1 = string.split(items1[0])
			if config.ipemail_debug: print(no1)
			for id in no1:
				resp,items1 = runtime.mbox.fetch(id, '(FLAGS RFC822.HEADER)')#header만
				text = items1[0][1]
				self.readFlag = items1[0][0]
				read = 0
				sent = 0
				if self.readFlag.find('SEEN') > -1 or self.readFlag.find('Seen')> -1:
					read = 1
				if self.readFlag.find('ANSWERED') > -1 or self.readFlag.find('Answered') > -1:
					sent = 1
				if config.ipemail_debug: print('***************FLAG:',self.readFlag)
				file = StringIO.StringIO(text)#header만...
				from email.Message import Message
				msg = rfc822.Message(file)
				toAddress = msg.get('to')
				fromAddress = msg.get('from')
				cc = msg.get('cc')
				bcc = msg.get('bcc')
				subject = msg.get('subject')
				date1 = msg.get('date')
				if not date1:
					y, m1, d, h, m2, s = time.localtime(ntptime.ntime())[:6]
					date1 = '%d %02d %02d %02d %02d %d %d' % (y, m1, d, h, m2, s, 0)
				else:
					tmp = date1[date1.rfind(',')+1:date1.rfind(':')+3]
					tmp = self.replaceMonth(tmp.strip())
					try:
						date1 =  time.strptime(tmp,'%d %m %Y %H:%M:%S')
						date1 = '%s %02d %02d %02d %02d %s %s' % date1[:7]
					except ValueError:#spam
						y, m1, d, h, m2, s = time.localtime(ntptime.ntime())[:6]
						date1 = '%d %02d %02d %02d %02d %d %d' % (y, m1, d, h, m2, s, 0)

				if str(msg).find('multipart') > -1:
					attach = ['0']#아무값으로 초기화.
				else:
					attach = []

				self.header_info.append([int(id), '', fromAddress, cc, bcc, subject, \
					date1, attach, read, sent, '', None])
				if config.ipemail_debug: print('mail header listing...',id,' fromAddress:',fromAddress,' read:',read)
		self.set_header_info(self.header_info)
		resp = []
		if setting.email_protocol == 'POP':
			resp = runtime.mbox.list()[1]
		else :
			def mk_format(tmpString):
				#'1 (RFC822.SIZE 1386)'
				tmpString = tmpString.replace('(','')
				tmpString = tmpString.replace('RFC822.SIZE','')
				tmpString = tmpString.replace(')','')
				tmpString = tmpString.replace('  ',' ')
				if config.ipemail_debug: print 'tmpString:',tmpString
				return tmpString
			for id in no1:
				resp2,items2 = runtime.mbox.fetch(id, '(RFC822.SIZE)')#size만
				#('OK',['1 (RFC822.SIZE 1386)'])
				if config.ipemail_debug: print 'id:',id, ' items2:',items2
				resp1 = mk_format(items2[0])
				resp.append(resp1)
		return resp
	"""

	def receive_header(self, inbox_num=0):
		import email
		if setting.email_protocol == 'POP':
			import poplib
		else:
			import imaplib
		self.header_info = []
		if config.ipemail_debug: print('receive message headers...')
		self.readFlag = 0

		#Roxia Begin cmlim 06.06.11
		down_num = 0
		noMsg = 0
		#Roxia End cmlim

		if setting.email_protocol == 'POP':
			noMsg, tsize = runtime.mbox.stat()
			if config.ipemail_debug:
				print 'receive_header', noMsg
			#Roxia Begin cmlim 06.06.10
			down_num = self.calc_DownNum(noMsg, inbox_num)
			#Roxia End cmlim

			#Roxia Begin cmlim 06.06.10
			#for k in range(1, noMsg+1):
			for k in range(1, down_num+1):
			#Roxia End cmlim
				res = runtime.mbox.top(k, 0)[1]

				headerMsg = '\n'.join(res)
				msg = email.message_from_string(headerMsg)
				toAddress = msg['to']
				fromAddress = msg['from']
				cc = msg['cc']
				bcc = msg['bcc']
				#Roxia Begin cmlim 06.04.06
				#subject = msg['subject']
				from ietp import decodeHeader
				subject = decodeHeader(msg['subject'])
				#Roxia End cmlim 06.04.06
				date1 = msg['date']
				if config.ipemail_debug: print date1
				if not date1:
					y, m1, d, h, m2, s = time.localtime(ntptime.ntime())[:6]
					date1 = '%d %02d %02d %02d %02d %d %d' % (y, m1, d, h, m2, s, 0)
					if config.ipemail_debug: print('IpEmailListStage no date exist:',date1)
				else:
					tmp = date1[date1.rfind(',')+1:date1.rfind(':')+3]
					tmp = self.replaceMonth(tmp.strip())
					try:
						date1 =  time.strptime(tmp,'%d %m %Y %H:%M:%S')
						date1 = '%s %02d %02d %02d %02d %s %s' % date1[:7]
					except ValueError:#spam
						y, m1, d, h, m2, s = time.localtime(ntptime.ntime())[:6]
						date1 = '%d %02d %02d %02d %02d %d %d' % (y, m1, d, h, m2, s, 0)
				# RHC / [20060824_1]
				if msg.get_content_type().startswith('multipart/alternative'):
					attach = []
				elif msg.get_content_type().startswith('multipart'):
					attach = ['0']#아무값으로 초기화.
				else:
					attach = []
				# RHC / [20060824_1]--
				read = 0#pop이면..무조건.
				sent = 0
				self.header_info.append((k, '', fromAddress, cc, bcc, subject, \
					date1, attach, read, sent, '', None))
		else:
			resp,items1 = runtime.mbox.search(None, 'ALL')
			#차례대로 아이템 붙이기
			import string,rfc822
			no1 = string.split(items1[0])

			#Roxia Begin cmlim 06.06.12
			noMsg = len(no1)
			down_num = self.calc_DownNum(len(no1), inbox_num)
			if config.ipemail_debug:
				print '^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^', len(no1), down_num
			#Roxia End cmlim

			if config.ipemail_debug: print(no1)
			#Roxia Begin cmlim 06.06.12
			#for id in no1:
			for i in range(down_num):
				id = no1[i]
			#Roxia End cmlim
				resp,items1 = runtime.mbox.fetch(id, '(FLAGS RFC822.HEADER)')#header만
				text = items1[0][1]
				self.readFlag = items1[0][0]
				read = 0
				sent = 0
				if self.readFlag.find('SEEN') > -1 or self.readFlag.find('Seen')> -1:
					read = 1
				if self.readFlag.find('ANSWERED') > -1 or self.readFlag.find('Answered') > -1:
					sent = 1
				if config.ipemail_debug: print('***************FLAG:',self.readFlag)
				file = StringIO.StringIO(text)#header만...
				from email.Message import Message
				msg = rfc822.Message(file)
				toAddress = msg.get('to')
				fromAddress = msg.get('from')
				cc = msg.get('cc')
				bcc = msg.get('bcc')
				#Roxia Begin cmlim 06.06.21
				#subject = msg.get('subject')
				from ietp import decodeHeader
				subject = decodeHeader(msg.get('subject'))
				#Roxia End cmlim
				date1 = msg.get('date')
				if not date1:
					y, m1, d, h, m2, s = time.localtime(ntptime.ntime())[:6]
					date1 = '%d %02d %02d %02d %02d %d %d' % (y, m1, d, h, m2, s, 0)
				else:
					tmp = date1[date1.rfind(',')+1:date1.rfind(':')+3]
					tmp = self.replaceMonth(tmp.strip())
					try:
						date1 =  time.strptime(tmp,'%d %m %Y %H:%M:%S')
						date1 = '%s %02d %02d %02d %02d %s %s' % date1[:7]
					except ValueError:#spam
						y, m1, d, h, m2, s = time.localtime(ntptime.ntime())[:6]
						date1 = '%d %02d %02d %02d %02d %d %d' % (y, m1, d, h, m2, s, 0)
				# RHC / [20060824_1]
				if str(msg).find('multipart/alternative') > -1:
					attach = []
				elif str(msg).find('multipart') > -1:
					attach = ['0']#아무값으로 초기화.
				else:
					attach = []
				# RHC / [20060824_1]--
				self.header_info.append([int(id), '', fromAddress, cc, bcc, subject, \
					date1, attach, read, sent, '', None])
				if config.ipemail_debug: print('mail header listing...',id,' fromAddress:',fromAddress,' read:',read)

		self.set_header_info(self.header_info)

		resp = []
		if setting.email_protocol == 'POP':
			resp = runtime.mbox.list()[1]
			#Roxia Begin cmlim 06.06.12
			resp = resp[0:down_num]
			#Roxia End cmlim
		else :
			def mk_format(tmpString):
				#'1 (RFC822.SIZE 1386)'
				tmpString = tmpString.replace('(','')
				tmpString = tmpString.replace('RFC822.SIZE','')
				tmpString = tmpString.replace(')','')
				tmpString = tmpString.replace('  ',' ')
				if config.ipemail_debug: print 'tmpString:',tmpString
				return tmpString
			#Roxia Begin cmlim 06.06.12
			#for id in no1:
			for i in range(down_num):
				id = no1[i]
			#Roxia End cmlim
				resp2,items2 = runtime.mbox.fetch(id, '(RFC822.SIZE)')#size만
				#('OK',['1 (RFC822.SIZE 1386)'])
				if config.ipemail_debug: print 'id:',id, ' items2:',items2
				resp1 = mk_format(items2[0])
				resp.append(resp1)

		#Roxia Begin cmlim 06.06.12
		#return resp
		return (resp, noMsg-down_num)
		#Roxia End cmlim

	def calc_DownNum(self, mail_num, inbox_num):
		down_num = 0
		if config.ipemail_entry_max <= inbox_num:
			if config.ipemail_debug:
				print 'receive_header', 'inbox is full', inbox_num
			if 0 < mail_num:
				# -> full message -> n more email -> inbox
				pass
			else:
				# -> inbox
				#변경되는 사항 없음.
				pass
		else:
			if config.ipemail_debug:
				print 'receive_header', 'inbox_num < 20', mail_num + inbox_num
			if config.ipemail_entry_max <= mail_num + inbox_num:
				# -> 20개 까지 받는다 -> n more eamil -> inbox
				down_num = config.ipemail_entry_max - inbox_num
			else:
				# -> inbox
				#변경되는 사항 없음.
				down_num = mail_num
				pass
		return down_num
	#Roxia End cmlim

	def merge_list(self):
		receivedInfo = ipemailmgr.make_received_info()#local과 header정보를 merge
		return receivedInfo

	def remove_msg(self, m):
		if config.ipemail_debug: print('Mgr.remove_msg')
		if config.ipemail_debug: print m.filename
		if self.read_path:
			if m.filename.startswith(self.read_path):#local
				l = list_get_inbox(self.read_info, m.filename)
				self.read_info.remove(l)
				utils.remove_file(m.filename)
				utils.remove_dir(m.filename+'Attach/')
				if os.path.exists(m.filename+'Attach/'):
					os.rmdir(m.filename+'Attach/')
				self.save_infos(0)
			else:#server
				pass
		if self.personal_path:
			if m.filename.startswith(self.personal_path):
				l = list_get(self.personal_info, m.filename)
				self.personal_info.remove(l)
				utils.remove_file(m.filename)
				self.save_infos(1)

		if self.sent_path:
			if m.filename.startswith(self.sent_path):
				l = list_get(self.sent_info, m.filename)
				self.sent_info.remove(l)
				utils.remove_file(m.filename)
				self.save_infos(2)

		if self.draft_path:
			if m.filename.startswith(self.draft_path):
				l = list_get(self.draft_info, m.filename)
				self.draft_info.remove(l)
				utils.remove_file(m.filename)
				self.save_infos(3)

	def count(self):
		return len(self.read_info)

	def count_unread(self):
		count = 0
		for index, filename, fromAddress, cc, bcc, subject, date, attach, \
			read, sent, content_type, body in self.received_info:
			if not read:
				count += 1
		return count

	def count_personal(self):
		return len(self.personal_info)

	def count_sent(self):
		return len(self.sent_info)

	def count_draft(self):
		return len(self.draft_info)

	def count_allipemail(self):
		read_info = ipemailmgr.reload(1)
		personal_info = ipemailmgr.reload(2)
		sent_info = ipemailmgr.reload(3)
		draft_info = ipemailmgr.reload(4)
		return self.count()+self.count_personal()+self.count_sent()+self.count_draft()

	def delete_msg_in_server(self,index):
		if config.ipemail_debug: print 'delete message.in.server.:',index,type(index),setting.email_protocol
		if setting.email_protocol == 'POP':
			import poplib
			runtime.mbox.dele(index) #메시지.삭제..
		else:
			import imaplib
			runtime.mbox.store(index,'+FLAGS','\\Deleted')
			runtime.mbox.expunge()
		if config.ipemail_debug: print 'ipemailmanager.delete_msg_in_server.end\n\n\n'

	#boxtype:  0 = received, 1 = personal(out), 2 = sent, 3 = draft
	def read_message(self, receivedIndex=1, readIndex=1, boxtype=0):#from local
		self.reload(boxtype + 1)
		if config.ipemail_debug: print('read_message')
		filename = ''

		if 0 == boxtype:
			for i, info in enumerate(self.read_info):
				if config.ipemail_debug: print('readIndex:',readIndex,' info[0]:',info[0])
				if config.ipemail_debug: print('readIndex:',type(readIndex),' info[0]:',type(info[0]))
				if info[0] == readIndex:
					index, filename, fromAddress, cc, bcc, subject, date, \
						attach, read, sent, content_type, body= info
					self.read_info[int(readIndex.replace('I','')) - 1][8] = 1#read mark
					self.save_infos()#apply
					break
		elif 1 == boxtype:
			for i, info in enumerate(self.personal_info):
				if info[0] == readIndex:
					index, filename, fromAddress, cc, bcc, subject, date, attach, \
						read, sent, content_type, body= info
					self.personal_info[receivedIndex] = \
						(receivedIndex, filename, fromAddress, cc, bcc, subject, \
						date, attach, 1, sent, content_type, body)
					break
		elif 2 == boxtype:
			if config.ipemail_debug: print 'sent read'
			for i, info in enumerate(self.sent_info):
				if info[0] == readIndex:
					index, filename, fromAddress, cc, bcc, subject, date, attach, \
						read, sent, content_type, body= info
					self.sent_info[receivedIndex] = \
						(receivedIndex, filename, fromAddress, cc, bcc, subject, \
						date, attach, 1, sent, content_type, body)
					break
		elif 3 == boxtype:
			if config.ipemail_debug: print 'draft read'
			for i, info in enumerate(self.draft_info):
				if info[0] == readIndex:
					index, filename, fromAddress, cc, bcc, subject, date, attach, \
						read, sent, content_type, body= info
					self.draft_info[receivedIndex] = \
						(receivedIndex, filename, fromAddress, cc, bcc, subject, \
						date, attach, 1, sent, content_type, body)
					break
		import ietp
		#위의 if내에서는 filename변수값 유의
		ipEmailMsg = ietp.IpEmailMessage()
		if config.ipemail_debug: print('ipEmailMsg.load:',filename)
		ipEmailMsg = ipEmailMsg.load(filename)
		del ietp

		return ipEmailMsg

	def get_received_info(self):
		return self.received_info

	def make_received_info(self):
		def cmp_func(i1, i2):
			#최근 시간이 위로 올라오게
			return cmp(i2[6], i1[6])

		# head_info와 합쳐야 한다.
		self.received_info = self.header_info + self.read_info
		self.received_info.sort(cmp_func)
		return self.received_info

	def get_sent_messages(self):
		return self.sent_info

	def get_draft_messages(self):
		return self.draft_info

	def get_personal_messages(self):
		return self.personal_info

	def remove_all_sent(self):
		utils.remove_dir(self.sent_path)
		self.sent_info = []
		self.save_infos(2)

	def remove_all_draft(self):
		utils.remove_dir(self.draft_path)
		self.draft_info = []
		self.save_infos(3)

	def remove_all_received_attach(self):
		try:
			for f in os.listdir(config.ip_email_read_path):
				name = config.ip_email_read_path + f
				stat = os.stat(name)
				if stat[0] & 0100000:
					try:
						utils.remove_dir(name+'Attach/')
						os.rmdir(name+'Attach/')
					except:
						pass
		except OSError:
			pass

	def remove_all_received(self):
		self.remove_all_received_attach()
		utils.remove_dir(self.read_path)
		self.read_info = []
		self.save_infos(0)

	def remove_all_saved(self):
		utils.remove_dir(self.personal_path)
		self.personal_info = []
		self.save_infos(1)

	def remove_all(self):
		self.remove_all_received()
		self.remove_all_saved()
		self.remove_all_sent()
		self.remove_all_draft()

	def countInboxCount(self):
		msg = self.reload(1)

		if msg:
			return len(msg)
		else:
			return 0

	def get_inbox_list(self):
		if setting.email_userid and setting.email_password and (setting.email_imapserver or setting.email_popserver):
			import uiconfig, time

			def convert_datetype(date1):
				t = date1.split(' ')
				if len(t) < 9:
					_len = 9 - len(t)+1
					for i in range(1,_len):
						t.append('0')
				elif len(t) > 9:
					_len = 9 - len(t) + 1
					for i in range(1, _len):
						t.pop()

				_t = []
				for w in t:
					_t.append(int(w))

				date2 = time.mktime(tuple(_t))
				return date2

			read_info = list(self.reload(1))
			returnList = []
			i = 0
			read_info = self.make_received_info()# date order sort..
			for idx, file, fromAddress, cc,bcc,subject, date, attach, read,sent,content_type,body in read_info:
				if not date:
					y, m1, d, h, m2, s = time.localtime(ntptime.ntime())[:6]
					date = '%d %02d %02d %02d %02d %d %d' % (y, m1, d, h, m2, s, 0)
				date = convert_datetype(date)
				# attach가 있는 경우 표시 아이콘을 달리한다.
				if sent:
					icons = uiconfig.list_icon_email_inbox_sent
				else:
					if read:
						# RHC / [20061115_3]
						if len(attach) != 0:
							icons = uiconfig.list_icon_email_inbox_read_attachment
						else:
							icons = uiconfig.list_icon_email_inbox_read
						# RHC / [20061115_3]--
					else:
						# RHC / [20061115_3]
						if len(attach) != 0:
							icons = uiconfig.list_icon_email_inbox_unread_attachment
						else:
							icons = uiconfig.list_icon_email_inbox_unread
						# RHC / [20061115_3]--
				#read_info의 idx값이 아니라, UI상의 list상의 index번호 이다.0,1,2,3,4,5,
				returnList.append(('email', date, subject, icons, i))
				i += 1
			return returnList

		else:
			if config.ipemail_debug: print 'HUK~~~'
			return []

class IpEmailManager(IpEmailManagerBase):
	draft_path = config.ip_email_draft_path
	draft_info_path = config.ip_email_draft_info_path
	sent_path = config.ip_email_sent_path
	sent_info_path = config.ip_email_sent_info_path

	read_path = config.ip_email_read_path
	read_info_path = config.ip_email_read_info
	personal_path = config.ip_email_saved_path
	personal_info_path = config.ip_email_personal_info

ipemailmgr = IpEmailManager()

class IpEmailServ:
	SOCK_FILE='/tmp/.IpEmailServ.sock'
	def __init__(self,argClass = None):
		try:
			os.unlink(self.SOCK_FILE)
		except OSError:
			pass
		self.argClass = argClass
		self.server_s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0)
		self.server_s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		self.server_s.bind(self.SOCK_FILE)
		self.server_s.listen(5)
		self.ipEmailServ_s = None
		self.ipEmailServ_tag = None

		self.server_tag = utils.Input(self.server_s.fileno(), self.accept_IpEmailServ)

		self.pid = os.fork()
		if not self.pid:
			if config.ipemail_debug: print "starting Ipemail processor"
			try:
				self.pid = os.getpid()
				if config.ipemail_debug: print 'IpEmailServ.pid:',self.pid
				exe_file = 'ipemailmanager.pyc'
				if os.path.exists('ipemailmanager.py'):
					exe_file = 'ipemailmanager.py'
				os.execlp('python','python',exe_file)
				#뒤에는 실행이 암됨.
			except:
				if config.ipemail_debug: print 'run failed'
				os._exit(1)

	def destroy(self):
		if config.ipemail_debug: print 'IpEmailServ.destroy.............'
		if config.ipemail_debug: print 'IpEmailServ pid = ', self.pid
		if self.pid:
			try:
				import signal
				os.kill(self.pid,signal.SIGKILL)
				# clean a zombie
				def hdl_sigchld(signum, frame):  # clean a zombie
					try:
					    	while 1:
						        if os.waitpid(0, os.WNOHANG): raise OSError
					except OSError:
					   	pass
				signal.signal(signal.SIGCHLD, hdl_sigchld)
				self.ipEmailServ_tag = None
				self.ipEmailServ_s = None
				os.unlink(self.SOCK_FILE)
			except:
				pass

	def accept_IpEmailServ(self, fd, type):
		self.ipEmailServ_s, addr = self.server_s.accept()
		self.ipEmailServ_tag = utils.Input(self.ipEmailServ_s.fileno(), self.handle_IpEmailServ)
		return True

	def recv_packet(self):
		try:
			c = self.ipEmailServ_s.recv(1)
			l = ord(c)
			msg = ''
			while l > 0:
				m = self.ipEmailServ_s.recv(l)
				l -= len(m)
				msg += m
			if config.ipemail_debug: print '###IpEmailServ.recv_packet(',msg,')'
		except AttributeError:
			pass
		except TypeError:
			pass
		except socket.error:
			pass
		return msg

	def send_packet(self, buf):
		try:
			import struct
			p = struct.pack('B', len(buf))
			self.ipEmailServ_s.send(p)
			self.ipEmailServ_s.send(buf)
			if config.ipemail_debug: print '*****IpEmailServ.send_packet(',buf,')'
		except AttributeError:
			pass
		except TypeError:
			pass
		except socket.error:
			pass

	def decode_msg_sizeStruct(self,file2):
		if config.ipemail_debug: print 'decode_msg_sizeStruct.file2:',file2
		f = open(file2,'r')
		fl = f.read()
		msgsize = decompose_address(fl)
		f.close()
		return msgsize

	def decode_tmpHeaderStruct(self,file1):
		if config.ipemail_debug: print 'decode_tmpHeaderStruct.file:',file1
		header_info = []
		index = 0
		filename = ''
		fromAddress = []
		cc = []
		bcc = []
		subject = ''
		date = ''
		attaches = []
		read = 0
		sent = 0
		body = ''
		idx = 0

		content_type = ''

		f = open(file1,'r')
		for line in f.xreadlines():#index,filename, fromAddress, cc,bcc,subject, date, attach, read,sent,body순
			line = line.strip()
			if idx == 0 :#처리 유의...space no no no
				if line.isdigit():index = int(line)
				else:index = line
			if idx == 1:
				filename = line
			elif idx == 2:fromAddress = decompose_address(line)
			elif idx == 3:cc = decompose_address(line)
			elif idx == 4:bcc = decompose_address(line)
			elif idx == 5:subject = line
			elif idx == 6:date = line
			elif idx == 7:
				attaches = decompose_address(line)
				if not attaches:attaches = []
			elif idx == 8:read = int(line)
			elif idx == 9:sent =  int(line)
			elif idx == 10:
				content_type = line
			elif idx == 11:body = line.rstrip()
			elif idx > 11:body += line.rstrip()
			if body.find('\0\0\0\0\0') > -1:
				body = body.replace('\0\0\0\0\0','')
				body += body.rstrip()
				if config.ipemail_debug: print index,filename, fromAddress, cc,bcc,subject, date, attaches, read,sent,content_type,body
				header_info.append([index,filename, fromAddress, cc, bcc, subject, date, attaches, \
					read, sent, content_type, content_type, body])
				body = ''
				idx = 0
				continue
			idx +=1
		f.close()
		if config.ipemail_debug: print 'decode_tmpHeaderStruct.end'
		return header_info

	def handle_IpEmailServ(self, fd, type):
		try:
			if type & evas.INPUT_HUP:
				return False

			_str = self.recv_packet()
			if config.ipemail_debug: print 'handle_IpEmailServ:',_str,runtime.manager.stage.name
			if _str == 'GOT_SPEED':
				if runtime.manager.stage.name == 'receive header'\
					or runtime.manager.stage.name == 'email processing':
					runtime.manager.stage.set_send_message()
			if _str == 'LOGIN_FAIL':
				if runtime.manager.stage.name == 'receive header'\
					or runtime.manager.stage.name == 'email processing':
					runtime.manager.stage.set_login_response(self.recv_packet())
			elif _str == 'RECEIVE_HEADER_RESPONSE':
				if runtime.manager.stage.name == 'receive header':
					#Roxia Begin cmlim 06.06.12
					remain_num = int(self.recv_packet())
					if config.ipemail_debug:
						print '!!!!!!!!!!!!!!!!! remain_num', remain_num
					#Roxia End cmlim
					ans = self.recv_packet()
					if ans != 'NO_SERVER_MAIL':
						#Roxia Begin cmlim 06.06.12
						#runtime.manager.stage.set_msg_sizes(self.decode_msg_sizeStruct(ans))
						runtime.manager.stage.set_msg_sizes(self.decode_msg_sizeStruct(ans), remain_num)
						#Roxia End cmlim
						utils.remove_file(ans)
					else:
						#Roxia Begin cmlim 06.06.12
						#runtime.manager.stage.set_msg_sizes(ans)
						runtime.manager.stage.set_msg_sizes(ans, remain_num)
						#Roxia End cmlim

						_str = ''
						return
					headerinfoFile = self.recv_packet()
					if config.ipemail_debug: print 'headerinfoFile:',headerinfoFile
					header_info1 = self.decode_tmpHeaderStruct(headerinfoFile)
					utils.remove_file(headerinfoFile)
				 	runtime.manager.stage.set_header_info(header_info1)
			elif _str == 'RECEIVE_MESSAGE_BODY_RESPONSE':#return msg size
				if runtime.manager.stage.name == 'email processing':
					#Roxia Begin cmlim 06.06.12
					remain_num = int(self.recv_packet())
					#Roxia End cmlim
					ans = self.recv_packet()
					if ans != 'NO_SERVER_MAIL':
						#Roxia Begin cmlim 06.06.12
						#runtime.manager.stage.set_msg_sizes(self.decode_msg_sizeStruct(ans))
						runtime.manager.stage.set_msg_sizes(self.decode_msg_sizeStruct(ans), remain_num)
						#Roxia End cmlim
						utils.remove_file(ans)
					else:
						#Roxia Begin cmlim 06.06.12
						#runtime.manager.stage.set_msg_sizes(ans)
						runtime.manager.stage.set_msg_sizes(ans, remain_num)
						#Roxia End cmlim
			elif _str == 'RECEIVE_HEADER_INFO_RESPONSE':#server header_info
				if runtime.manager.stage.name == 'email processing':
					print 'handle_IpEmailServ RECEIVE_HEADER_INFO_RESPONSE'
					#Roxia Begin cmlim
					remain_num = int(self.recv_packet())
					#Roxia End cmlim

					headerinfoFile = self.recv_packet()
					header_info = self.decode_tmpHeaderStruct(headerinfoFile)
					utils.remove_file(headerinfoFile)
				 	runtime.manager.stage.set_header_info(header_info)
			elif _str == 'act_ended':
				if runtime.manager.stage.name == 'email processing':
					runtime.manager.stage.act_ended()
			elif _str == 'DESTROY':
				if config.ipemail_debug: print 'xxx'
				self.destroy()
			_str = ''
		except:
			self.destroy()
		return True

class IpEmailAction:
	SOCK_FILE='/tmp/.IpEmailServ.sock'

	def __init__(self):
		self.client_s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0)
		self.client_s.connect(self.SOCK_FILE)

	def recv_packet(self):
		try:
			c = self.client_s.recv(1)
			l = ord(c)
			msg = ''
			while l > 0:
				m = self.client_s.recv(l)
				l -= len(m)
				msg += m
			if config.ipemail_debug: print 'IpEmailAction.recv_packet:',msg
			return msg
		except TypeError:
			pass
		except AttributeError:
			return ''
		except socket.error:
			return ''

	def send_packet(self, buf):
		try:
			import struct
			if config.ipemail_debug: print type(buf),buf
			p = struct.pack('B', len(buf))
			self.client_s.send(p)
			self.client_s.send(buf)
		except TypeError:
			pass
		except AttributeError:
			pass
		except socket.error:
			pass

	def save_msg_sizeStruct(self,msg_sizes):
		tmpFileName = tempfile.mktemp()
		fp = open(tmpFileName,'w')
		fp.write(compose_address(msg_sizes))
		fp.close()
		return tmpFileName


	def save_tmpHeaderStruct(self,info):
		def del_carrige_return(tmp):
			ret_tmp = []
			if type(tmp) == str:
				ret_tmp.append(tmp.replace('\n',''))
			elif type(tmp) == list:
				for d in tmp:
					d = d.replace('\n','')
				ret_tmp = tmp
			return compose_address(ret_tmp)

		tmpFileName = tempfile.mktemp()
		if info:
			fp = open(tmpFileName,'w')
			for  d in info:
				index, filename, fromAddress, cc, bcc, subject, date, attaches,\
					read, sent, content_type, body= d
				fp.write(str(index)+ '\n')
				fp.write(filename+ '\n')
				if fromAddress: fp.write(del_carrige_return(fromAddress) + '\n')
				else:fp.write('\n')

				if cc: fp.write(del_carrige_return(cc) + '\n')
				else: fp.write('\n')

				if bcc: fp.write(del_carrige_return(bcc) + '\n')
				else: fp.write('\n')
				fp.write(subject.replace('\n','') + '\n')#흐미 subject에 CR/LF가 들어가부러야~
				import time, ntptime
				if date:
					if config.ipemail_debug: print date,type(date)
					if type(date) != time.struct_time and type(date) != tuple:#not already converted numeric date
						tmp = date[date.rfind(',')+1:date.rfind(':')+3]
						tmp = ipemailmgr.replaceMonth(tmp.strip())
						try:
							date =  time.strptime(tmp,'%d %m %Y %H:%M:%S')
							date = '%s %02d %02d %02d %02d %s %s' % date[:7]
							fp.write(date+ '\n')
						except ValueError:#spam
							y, m1, d, h, m2, s = time.localtime(ntptime.ntime())[:6]
							date = time2 = (y, m1, d, h, m2, s, 0)
							fp.write('%d %02d %02d %02d %02d %d %d' % tuple(time2) + '\n')
					else:#numeric str
						fp.write(date+ '\n')
				else:
					y, m1, d, h, m2, s = time.localtime(ntptime.ntime())[:6]
					time = (y, m1, d, h, m2, s, 0)
					fp.write('%d %02d %02d %02d %02d %d %d' % tuple(time) + '\n')
				fp.write(compose_address(attaches)+ '\n')
				fp.write('%s' % read + '\n')
				fp.write('%s' % sent + '\n') # 0:False 1:True
				fp.write('%s' % content_type + '\n')
				if body:
					fp.write(body + '\n')
				else:
					fp.write('\n')
				fp.write('\0\0\0\0\0\n')
			fp.close()
		return tmpFileName

	def receive_message(self, receivedIndex=1, headerIndex=1):#download
		try:
			if utils.get_file_count(ipemailmgr.read_path) >= config.ipemail_entry_max:
				raise StorageFullError, 'Storage Full'
				#걸러진 애들은 지우지도 말아야한다...********************
			if config.ipemail_debug: print('recv_message:',receivedIndex,headerIndex)

			if setting.email_protocol == 'POP':
				import poplib
				(server_msg, body, octets) = runtime.mbox.retr(headerIndex)
				message = '\n'.join(body)#header포함된 메시지.
				# RHC / [20061124_4]
				message = message + '\x0a'
				# RHC / [20061124_4]--
			else:
				import imaplib
				resp,body = runtime.mbox.fetch(headerIndex, '(RFC822)')
				body = body[0][1]
				message = ''.join(body)

			import ietp
			newFilename = ipemailmgr.read_path+ietp.get_last_temp_mail_filename(ipemailmgr.read_path)
			ipemailmgr.reload(1)
			ipEmailMsg = ietp.IpEmailMessage()
			ipEmailMsg.parseMessage(message,newFilename)

			if config.ipemail_debug: print 'self.header_info:',ipemailmgr.header_info
			for i, info in enumerate(ipemailmgr.header_info):
				if config.ipemail_debug: print ' info[0]:',info[0],' headerIndex:',headerIndex
				if config.ipemail_debug: print ' info[0]:',type(info[0]),' headerIndex:',type(int(headerIndex))
				if info[0] == int(headerIndex):
					if config.ipemail_debug: print 'OKOKOKOK~~'
					index, filename, fromAddress, cc, bcc, subject, \
						date, attach, read, sent, content_type, body = info
					attach = ipEmailMsg.attaches#파싱하면서 가져온 파일명을 저장.
					body = ipEmailMsg.body
					ipemailmgr.read_info.append(['', newFilename, fromAddress, cc, \
						bcc, subject, date, attach, '0', sent, content_type, body])
					ipemailmgr.save_infos()
					break;
			del ietp
			return ipEmailMsg
		except StorageFullError:
			return None

	def run(self):
		realnotDel = []
		#Roxia Begin cmlim 06.06.09
		import time
		time.sleep(5)
		inbox_num = 0
		#Roxia End cmlim
		self.send_packet('GOT_SPEED')
		while 1:
			try:
				_str = self.recv_packet()
			except:
				break

			if _str == 'RECEIVE_HEADER_REQUEST':#IpEmailReceiverStage...
				#Roxia Begin cmlim 06.06.10
				#self.inbox_num = 0
				_str = self.recv_packet()
				#self.inbox_num = int(_str)
				inbox_num = int(_str)
				if config.ipemail_debug:
					print 'RECEIVE_HEADER_REQUEST', _str, inbox_num
				#Roxia End cmlim
				logining = ipemailmgr.mail_log_in() # 1: success, 0: wrong login info, -2:can't find server, 111: connection refused
				if logining != 1:#not success
					self.send_packet('LOGIN_FAIL')
					self.send_packet(str(logining))
					_str = ''
					continue
				#Roxia Begin cmlim 06.06.10
				#msg_sizes = ipemailmgr.receive_header()
				msg_sizes = ipemailmgr.receive_header(inbox_num)
				#Roxia End cmlim
				self.send_packet('RECEIVE_HEADER_RESPONSE')

				#Roxia Begin cmlim 06.06.12
				self.send_packet(str(msg_sizes[1]))
				#Roxia End cmlim

				#Roxia Begin cmlim 06.06.12
				#if msg_sizes:
				#	self.send_packet(self.save_msg_sizeStruct(msg_sizes))
				#else:
				#	self.send_packet('NO_SERVER_MAIL')
				#	continue
				if msg_sizes[0]:
					self.send_packet(self.save_msg_sizeStruct(msg_sizes[0]))
				else:
					self.send_packet('NO_SERVER_MAIL')
					continue
				#Roxia End cmlim

				fName = self.save_tmpHeaderStruct(ipemailmgr.get_header_info())
				self.send_packet(fName)

				ipemailmgr.mail_log_out()
				if config.ipemail_debug:
					print '~~~~~~ run receive_header end'

			elif _str == 'RECEIVE_MESSAGE_BODY_REQUEST':#return msg size#processingStage...
				if config.ipemail_debug:
					print '%%%%% RECEIVE_MESSAGE_BODY_REQUEST %%%%%'
				#Roxia Begin cmlim 06.06.12
				_str = self.recv_packet()
				inbox_num = int(_str)
				#Roxia End cmlim
				logining = ipemailmgr.mail_log_in() # 1: success, 0: wrong login info, -2:can't find server, 111: connection refused
				if logining != 1:#not success
					self.send_packet('LOGIN_FAIL')
					self.send_packet(str(logining))
					_str = ''
					continue

				#Roxia Begin cmlim 06.06.12
				#msg_sizes = ipemailmgr.receive_header()
				msg_sizes = ipemailmgr.receive_header(inbox_num)
				#Roxia End cmlim
				self.send_packet('RECEIVE_MESSAGE_BODY_RESPONSE')
				#Roxia Begin cmlim 06.06.12
				#if msg_sizes:
				#	self.send_packet(self.save_msg_sizeStruct(msg_sizes))
				#else:
				#	self.send_packet('NO_SERVER_MAIL')
				self.send_packet(str(msg_sizes[1]))
				if msg_sizes[0]:
					self.send_packet(self.save_msg_sizeStruct(msg_sizes[0]))
				else:
					self.send_packet('NO_SERVER_MAIL')
				#Roxia End cmlim
			elif _str == 'RECEIVE_DOWNLOAD_BODY_REQUEST':#server download msg body
				if config.ipemail_debug:
					print '%%%%% RECEIVE_DOWNLOAD_BODY_REQUEST %%%%%'
				downlist = decompose_address(self.recv_packet())
				if config.ipemail_debug: print 'downlist:',downlist
				for d in downlist:
					if not self.receive_message(0,int(d)):
						realnotDel.append(int(d))#못받은 메시지는 기억해
			elif _str == 'INBOX_MESSAGE_DELETE_REQUEST':#server delete index msg
				if config.ipemail_debug:
					print '%%%%% INBOX_MESSAGE_DELETE_REQUEST %%%%%'
				delList = decompose_address(self.recv_packet())
				if config.ipemail_debug: print 'delList:',delList
				for d in delList:
					if realnotDel:
						if int(d) in realnotDel:#못받은 메시지는 안지워야 한다.
							if config.ipemail_debug: print '못받은 메시지:',int(d)
						else:
							ipemailmgr.delete_msg_in_server(int(d))
					else:
						ipemailmgr.delete_msg_in_server(int(d))
				realnotDel = []
				self.send_packet('act_ended')

			elif _str == 'RECEIVE_HEADER_INFO_NO_LOGIN_REQUEST':
				if config.ipemail_debug:
					print '%%%%% RECEIVE_HEADER_INFO_NO_LOGIN_REQUEST %%%%%'
				#Roxia Begin cmlim 06.06.12
				##_str = self.recv_packet()
				##inbox_num = int(_str)
				#Roxia End cmlim
				self.send_packet('RECEIVE_HEADER_INFO_RESPONSE')
				ipemailmgr.reload()
				#Roxia Begin cmlim
				#ipemailmgr.receive_header()
				if config.ipemail_debug:
					print '---------- RECEIVE_HEADER_INFO_NO_LOGIN_REQUEST read_info',  len(ipemailmgr.read_info)
				inbox_num = len(ipemailmgr.read_info)
				remain_num = ipemailmgr.receive_header(inbox_num)[1]
				self.send_packet(str(remain_num))
				if config.ipemail_debug:
					print '--------', remain_num
				#Roxia End cmlim

				receiveHeader = ipemailmgr.merge_list()
				fName = self.save_tmpHeaderStruct(receiveHeader)
				self.send_packet(fName)

			elif _str == 'RECEIVE_HEADER_INFO_REQUEST':#received_info를 주면 된다.server+ local = merge
				if config.ipemail_debug:
					print '%%%%% RECEIVE_HEADER_INFO_REQUEST %%%%%'
				logining = ipemailmgr.mail_log_in() # 1: success, 0: wrong login info, -2:can't find server, 111: connection refused
				if logining != 1:#not success
					self.send_packet('LOGIN_FAIL')
					self.send_packet(str(logining))
					_str = ''
					continue

				if config.ipemail_debug:
					print 'RECEIVE_HEADER_INFO_REQUEST-RECEIVE_HEADER_INFO_RESPONSE'
				self.send_packet('RECEIVE_HEADER_INFO_RESPONSE')


				ipemailmgr.reload()
				#Roxia BEgin cmlim 06.06.12
				#ipemailmgr.receive_header()
				inbox_num = len(ipemailmgr.read_info)
				remain_num = ipemailmgr.receive_header(inbox_num)[1]
				self.send_packet(str(remain_num))
				#Roxia End cmlim
				receiveHeader = ipemailmgr.merge_list()
				fName = self.save_tmpHeaderStruct(receiveHeader)
				self.send_packet(fName)

			elif _str == 'LOGOUT':
				ipemailmgr.mail_log_out()
				self.send_packet('DESTROY')
			_str = ''


if __name__ == '__main__':#ipemail_Client run
	if config.ipemail_debug: print '\n\n\n\n\n\n\nipemail_Client(IpEmailAction) run()~~~'
	ipEmailAction = IpEmailAction()
	ipEmailAction.run()