Newer
Older
Import / projects / LGN-IP3870 / t / orig / ietp.py
import utils
from setting import setting
import mimetypes
from roxiadebug import *
import smtplib

class StorageFullError(Exception):
	pass

def get_last_temp_mail_filename(dirs = None):
	import os
	i = 0
	while True:
		filename = dirs + '%08d' % i
		if not os.path.exists(filename):
			break

		i += 1
		continue
	return '%08d' % i

#Roxia Begin cmlim 06.04.05
def trans_charset(char_set, msg):
	if config.ipemail_debug:
		print '@@@@@@########@@@@trans_charset', char_set

	new_msg = ''
	if 'ks_c_5601-1987' == char_set or 'euc_kr' == char_set or 'euc-kr' == char_set:
		new_msg = unicode(msg, 'euc-kr')
		new_msg = unicode(new_msg).encode('utf-8')
	elif 'iso8859-1' == char_set or 'iso-8859-1' == char_set:
		new_msg = unicode(msg, 'iso8859-1')
		new_msg = unicode(new_msg).encode('utf-8')
	elif 'windows-1252' == char_set:
		new_msg = unicode(msg, 'iso8859-1')
		new_msg = unicode(new_msg).encode('utf-8')
	else:
		new_msg = msg

	return new_msg
#Roxia End cmlim 06.04.05

def decodeHeader(headerMsg):
	from email import Header
	L = Header.decode_header(headerMsg)
	#Roxia Begin cmlim 06.04.05
	#return ''.join([t[0] for t in L])
	string = ''.join([t[0] for t in L])
	return trans_charset(L[0][1], string)
	#Roxia End cmlim 06.04.05

class IpEmailMessage:
	def __init__(self, subject=None, fromAddress=None, toAddress=None,  date=None, attaches=None):
		self.host = setting.email_smtpserver
		self.msg = ''
		self.filename = ''
		if fromAddress:
			self.fromAddress = fromAddress
		else:
			self.fromAddress = []
		if subject:
			self.subject = subject
		else:
			self.subject = ''
		if toAddress:
			self.toAddress = [toAddress]
		else:
			self.toAddress = []
		self.cc = []
		self.bcc = []
		self.body = ''
		if attaches:
			self.attaches = [attaches]
		else:
			self.attaches = []
		if date:
			self.date = date
		else:
			self.date = ''
		self.read = 0
		self.sent = 0
		self.content_type = ''

	def send(self):
		import evas,runtime
		runtime.evas.render_now()
		def make_message():
			from email.MIMEText import MIMEText
			if config.ipemail_debug: print('send...toAddress:',self.toAddress,' self.attaches:',self.attaches)
			if not self.attaches:
				outer = MIMEText(self.body)
				outer['Subject'] = self.subject
				outer['From'] = self.fromAddress
				outer['To'] = ','.join(self.toAddress)
			else:
				from email.MIMEMultipart import MIMEMultipart
				outer = MIMEMultipart()
				outer['Subject'] = self.subject
				outer['From'] = self.fromAddress
				outer['To'] = ','.join(self.toAddress)

				from email.MIMEAudio import MIMEAudio
				from email.MIMEBase import MIMEBase
				from email.MIMEImage import MIMEImage

				for fileName in self.attaches:
					ctype, encoding = mimetypes.guess_type(fileName)

					if ctype is None or encoding is not None:
						ctype = 'application/octet-stream'
					if config.ipemail_debug: print('sent for fileName:',fileName,'; ctype:',ctype,' encoding:',encoding)
					maintype, subtype = ctype.split('/', 1)
					if maintype == 'text':
						fd = open(fileName)
						msg = MIMEText(fd.read(), _subtype=subtype)
					elif maintype == 'image':
						fd = open(fileName, 'rb')
						msg = MIMEImage(fd.read(), _subtype=subtype)
					elif maintype == 'audio':
						fd = open(fileName, 'rb')
						msg = MIMEAudio(fd.read(), _subtype=subtype)
					else:
						fd = open(fileName, 'rb')
						msg = MIMEBase(maintype, subtype)
					msg.set_payload(fd.read())
					# Encode the payload using Base64
					from email import Encoders
					Encoders.encode_base64(msg)
					fd.close()
					msg.add_header('Content-Disposition', 'attachment', filename=fileName)
					outer.attach(msg)
			if config.ipemail_debug: print('smtpServer:'+self.host+'\n'+outer.as_string())
			self.host = setting.email_smtpserver
			s = smtplib.SMTP(self.host)
			s.set_debuglevel(1)
			s.sendmail(self.fromAddress, self.toAddress, outer.as_string())
			s.quit()
		runtime.evas.idle_add(make_message)



	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 save(self, filename = None, boxtype=0):
		if config.ipemail_debug: print('ietp...read.info.save..filename:',filename)
		from ipemailmanager import compose_address
		if not filename:
			filename = self.filename
		else:
			self.filename = filename
		fp = open(filename, 'w')
		fp.write(self.filename+ '\n')
		if boxtype:
			fp.write(compose_address(self.toAddress) + '\n')
		else:
			fp.write(compose_address(self.fromAddress) + '\n')
		fp.write(compose_address(self.cc) + '\n')
		fp.write(compose_address(self.bcc) + '\n')

		fp.write(self.subject + '\n')
		import time, ntptime
		if self.date:
			if config.ipemail_debug: print 'SAVE>>>>>>>>>>>>self.date',self.date
			if config.ipemail_debug: print self.date,type(self.date)
			if type(self.date) == tuple:
				self.date = '%s %02d %02d %02d %02d %s %s' % self.date[:7]
			if type(self.date) != time.struct_time and type(self.date) != tuple:#already converted numeric date
				tmp = self.date[self.date.rfind(',')+1:self.date.rfind(':')+3]
				tmp = self.replaceMonth(tmp.strip())
				try:
					self.date =  time.strptime(tmp,'%d %m %Y %H:%M:%S')
					self.date = '%s %02d %02d %02d %02d %s %s' % self.date[:7]
					fp.write(self.date+ '\n')
				except ValueError:#spam
					y, m1, d, h, m2, s = time.localtime(ntptime.ntime())[:6]
					self.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(self.date+ '\n')
		else:
			if config.ipemail_debug: print 'save.self.date else'
			y, m1, d, h, m2, s = time.localtime(ntptime.ntime())[:6]
			self.time = (y, m1, d, h, m2, s, 0)
			fp.write('%d %02d %02d %02d %02d %d %d' % tuple(self.time) + '\n')

		fp.write(compose_address(self.attaches)+ '\n')
		fp.write('%s' % self.read + '\n')
		fp.write('%s' % self.sent + '\n') # 0:False 1:True
		#email.add contenttype
		fp.write('%s' % self.content_type + '\n')
		if self.body:
			fp.write(self.body)
		else:
			fp.write('\n')
		fp.close()

	#message를 메일서버로 부터 받아서 로컬에 저장하는 기능의 함수.multifile saving.....
	def parseMessage(self, mess,filename1):
		#Roxia Begin cmlim 06.04.05
		#def trans_charset(char_set, msg):
		#	if config.ipemail_debug:
		#		print 'trans_charset', char_set, msg
		#
		#	new_msg = ''
		#	if 'ks_c_5601-1987' == char_set or 'euc_kr' == char_set or \
		#	'euc-kr' == char_set:
		#		new_msg = unicode(msg, 'euc-kr')
		#		new_msg = unicode(new_msg).encode('utf-8')
		#	elif 'iso8859-1' == char_set or 'iso-8859-1' == char_set:
		#		new_msg = unicode(msg, 'iso8859-1')
		#		new_msg = unicode(new_msg).encode('utf-8')
		#	elif 'windows-1252' == char_set:
		#		new_msg = unicode(msg, 'iso8859-1')
		#		new_msg = unicode(new_msg).encode('utf-8')
		#	else:
		#		new_msg = msg
		#
		#	return new_msg
		#Roxia Begin cmlim 06.04.05
		import email

		# RHC / [20060802_1]
		#self.msg = email.message_from_string(mess)
		unixMessage = mess.replace('\x0d\x0a', '\x0a')
		self.msg = email.message_from_string(unixMessage)
		# RHC / [20060802_1]--

		self.filename = filename1
		filepath = self.filename[:self.filename.rfind('/')+1]
		try:
			self.subject = decodeHeader(self.msg['Subject'])
			#Roxia Begin spree 06.08.24
			self.subject = self.subject.replace('\n', '')
			# RHC / [20061111_1]
			self.subject = self.subject.replace('\t', '')
			# RHC / [20061111_1]--
			#Roxia End spree
			if config.ipemail_debug: print('parseMessage subject..:',self.subject)
			self.fromAddress = decodeHeader(self.msg['From'])
			self.toAddress.append(decodeHeader(self.msg['To']))
			import time, ntptime

			#여기서는 date 값만 채우고 에러시에 처리만해주고 아래 save()함수가 세부 처리.
			try:
				self.date = self.msg['Date']
				if self.date:
					if config.ipemail_debug: print 'parseMessage>>>>>date exist'
					tmp = self.date[self.date.rfind(',')+1:self.date.rfind(':')+3]
					tmp = self.replaceMonth(tmp.strip())
					self.date =  time.strptime(tmp,'%d %m %Y %H:%M:%S')
					self.date = '%s %02d %02d %02d %02d %s %s' % self.date[:7]
				else:
					if config.ipemail_debug: print 'parseMessage>>>>no date..'
					y, m1, d, h, m2, s = time.localtime(ntptime.ntime())[:6]
					self.date = '%d %02d %02d %02d %02d %d %d' % (y, m1, d, h, m2, s, 0)
			except:
				y, m1, d, h, m2, s = time.localtime(ntptime.ntime())[:6]
				self.date = '%d %02d %02d %02d %02d %d %d' % (y, m1, d, h, m2, s, 0)
				if config.ipemail_debug: print 'parseMessage>>>>>>>error>>self.date',self.date

			if config.ipemail_debug: print 'parseMessage>>>>>>>>>>>>self.date',self.date
			multi = False
			counter = 1
			first = True
			for part in self.msg.walk():
				if config.ipemail_debug:
					print 'part.contents-type:',part.get_main_type(),'type:',part.get_type()
					print 'body: ', part.get_payload(decode=False)
					print 'charset:', part.get_content_charset()
					print 'encoding', part.get_params(None,'Content-Transfer-Encoding',True)

				if part.get_main_type() == 'multipart':
					origin_filename = self.filename[self.filename.rfind('/')+1:]+'Attach/'
					utils.make_dir(filepath + origin_filename) #full path로 넣어야 되네.
					if config.ipemail_debug: print('dir created: ',filepath + origin_filename,' origin filename:',origin_filename)
					multi = True
					continue
				if multi:
					ext = ''
					filename = part.get_filename()
					if not filename:
						pass
					else:
						filename = filepath + origin_filename+filename

					if config.ipemail_debug: print('reading ...filename.....',first, filename)
					counter += 1

					b = part.get_payload(decode=True)
					if first:
						#email.add contenttype
						self.content_type = part.get_type()
						b = trans_charset(part.get_content_charset(), b)
						self.body = b
						first = False
						continue
					if b:
						if filename:
							fp = open(filename, 'wb')
							fp.write(b)

							fp.close()
							if not utils.check_free_storage('email',utils.get_size_kb(filename)):
								utils.remove_file(filename)
								raise StorageFullError, 'Storage Full'
								break
							self.attaches.append(filename)
						first = False
				else:
					#email.add contenttype
					self.content_type = part.get_type()

					self.body = part.get_payload(decode=1)
					self.body = trans_charset(part.get_content_charset(), self.body)

			self.save(self.filename)
		except StorageFullError:
			if config.ipemail_debug: print('ietp.parseMessage() StorageFullError')
		except:
			if config.ipemail_debug: print('************ietp.parseMessage.error...' )
		if config.ipemail_debug: print('ietp.parseMessage() end')
		return self

	def load(self, filename):
		self.filename = filename
		#modify ToAddr
		if config.ipemail_debug: print 'ietp.load', filename
		binbox = True
		if -1 == self.filename.find('read'):
			binbox = False
		try:
			from ipemailmanager import decompose_address

			fp = open(filename, 'r')
			idx = 0
			for line in fp.xreadlines():#filename, fromAddress, cc,bcc,subject, date, attach, read,sent,body순
				if idx < 9:
					line = line.strip()
				if idx == 0:
					self.filename = line
				elif idx == 1:
					#modify ToAddr
					if config.ipemail_debug: print 'idx == 1', line
					if binbox:
						if config.ipemail_debug: print 'binbox',binbox
						self.fromAddress = decompose_address(line)
					else:
						if config.ipemail_debug: print 'binbox false'
						self.toAddress = decompose_address(line)
					if config.ipemail_debug: print 'idx == 1out', self.toAddress
				elif idx == 2:
					self.cc = decompose_address(line)
				elif idx == 3:
					self.bcc = decompose_address(line)
				elif idx == 4:
					self.subject = line
				elif idx == 5:
					self.date = line
				elif idx == 6:
					self.attaches = decompose_address(line)
					if not self.attaches:
						self.attaches = []
				elif idx == 7:
					self.read = int(line)
				elif idx == 8:
					bsent = 1
					if 0 == int(line):
						bsent = 0
					self.sent = bsent
				elif idx == 9:
					self.content_type = line.rstrip()
				elif idx == 10:
					# RHC / [20061118_2]
					if line == '\n':
						self.body = ''
					else:
						self.body = line
					# RHC / [20061118_2]--
				elif idx > 10:self.body += line

				idx +=1
			if config.ipemail_debug: print('ietp.load() self.body:',self.body)
			fp.close()
		except:
			if config.ipemail_debug: print('************ietp.load.except....' )
		if config.ipemail_debug: print('ietp.load() end')
		return self