Newer
Older
Import / projects / LGN-IP3870 / t / new / ipemailsend.py
import socket
import mimetypes
import smtplib
from ipemaildefine import *

class IpEmail_Comm:
	def __init__(self):
		self.m_client_s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0)
		self.m_client_s.connect('/tmp/.ipemail.sock')

	def UnPack(self, buf):
		longint = 0
		for i in range(len(buf)):
			longint = longint << 8
			longint = longint + ord(buf[len(buf)-1-i])
		return longint

	def Recv_Packet(self):
		c = self.m_client_s.recv(4)
		packetlen = self.UnPack(c)
		msg = ''
		while packetlen > 0:
			m = self.m_client_s.recv(1)
			packetlen -= len(m)
			msg += m
		return msg

	def Send_Packet(self, buf):
		import struct
		p = struct.pack('B', len(buf))
		self.m_client_s.send(p)
		self.m_client_s.send(buf)

class IpEmailSend:
	def __init__(self):
		self.host = ''
		self.fromAddress = ''
		self.subject = ''
		self.toAddress = ''
		self.cc = ''
		self.bcc = ''
		self.body = ''
		self.attaches = []
		self.date = ''
		self.userid = ''
		self.password = ''
		self.toAddresslist = []
		self.cclist = []
		self.bcclist = []

		self.smtpauth = ''
		self.smtpid = ''
		self.smtppass = ''

	def Set_SendMessage(self, sendinfo):
		for i in sendinfo:
			if IPEMAIL_SENDINFO_HOST == i[0]:
				self.host = i[1]
			elif IPEMAIL_SENDINFO_FROM == i[0]:
				self.fromAddress = i[1]
			elif IPEMAIL_SENDINFO_SUBJECT == i[0]:
				self.subject = i[1]
			elif IPEMAIL_SENDINFO_TO == i[0]:
				self.toAddress = i[1]
				self.toAddresslist = self.toAddress.split(',')
			elif IPEMAIL_SENDINFO_CC == i[0]:
				self.cc = i[1]
				self.cclist = self.cc.split(',')
			elif IPEMAIL_SENDINFO_BCC == i[0]:
				self.bcc = i[1]
				self.bcclist = self.bcc.split(',')
			elif IPEMAIL_SENDINFO_BODY == i[0]:
				self.body = i[1]
			elif IPEMAIL_SENDINFO_ATTACH == i[0]:
				self.attaches = i[1].split(',')
				if 1 == len(self.attaches) and '' == self.attaches[0]:
					self.attaches = []
			elif IPEMAIL_SENDINFO_USERID == i[0]:
				self.userid = i[1]
			elif IPEMAIL_SENDINFO_PASS == i[0]:
				self.password = i[1]
			elif IPEMAIL_SENDINFO_SMTPAUTH == i[0]:
				self.smtpauth = i[1]
			elif IPEMAIL_SENDINFO_SMTPID == i[0]:
				self.smtpid = i[1]
			elif IPEMAIL_SENDINFO_SMTPPASS == i[0]:
				self.smtppass = i[1]

	def Send_Mail(self):
		def get_send_date():
			from time import gmtime, strftime
			return strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())

		from email.MIMEText import MIMEText

		if not self.toAddresslist[0]:
			self.toAddresslist = []
		if self.cclist[0]:
			self.toAddresslist += self.cclist
		if self.bcclist[0]:
			self.toAddresslist += self.bcclist
		if not self.attaches:
			outer = MIMEText(self.body, _charset='utf-8')
			outer['Subject'] = self.subject
			outer['From'] = self.fromAddress
			outer['To'] = self.toAddress
			outer['Cc'] = self.cc
			outer['Bcc'] = self.bcc
			outer['Date'] = get_send_date()
			#outer['Disposition-Notification-To'] = self.fromAddress
		else:
			from email.MIMEMultipart import MIMEMultipart
			from email.MIMEAudio import MIMEAudio
			from email.MIMEBase import MIMEBase
			from email.MIMEImage import MIMEImage
			from email.Message import Message

			outer = MIMEBase('multipart','mixed')
			outer['Subject'] = self.subject
			outer['From'] = self.fromAddress
			outer['To'] = self.toAddress
			outer['Cc'] = self.cc
			outer['Bcc'] = self.bcc
			outer['Date'] = get_send_date()
			outer.preamble = '\n\n'
			outer.epilogue=''
			msg = MIMEText(_text=self.body, _charset='utf-8')
			outer.attach(msg)

			del msg

			import os.path
			for fileName in self.attaches:
				if not os.path.exists(fileName):
					continue
				ctype, encoding = mimetypes.guess_type(fileName)

				if ctype is None or encoding is not None:
					ctype = 'application/octet-stream'
				maintype, subtype = ctype.split('/', 1)
				if maintype == 'text':
					fd = open(fileName)
					msg = MIMEText(fd.read(), _subtype=subtype, _charset='utf-8')
				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())
					from email import Encoders
					Encoders.encode_base64(msg)

				fd.close()
				msg.add_header('Content-Disposition', 'attachment', \
					filename=os.path.split(fileName)[1])
				outer.attach(msg)

				del msg
		try:
			outerasstring = outer.as_string()

#			fd = open('outerasstring.eml', 'wb+')
#			fd.write(outerasstring)
#			fd.close()

			del outer

			s = smtplib.SMTP(self.host)

			if 'Yes' == self.smtpauth:
				s.ehlo()
				# RHC / [20060914_1]
				#s.esmtp_features["auth"] = "LOGIN"
	 			try:
					s.login(self.smtpid, self.smtppass)
				# login()에 대한 exception 처리를 추가함.
				except smtplib.SMTPAuthenticationError:
					if config.ipemail_debug: 
						print 'wrong smtp server or login infomation'
					return False, IPEMAIL_ERRORTYPE_AUTH
				except smtplib.SMTPHeloError:
					if config.ipemail_debug: 
						print 'The server didn\'t reply properly to the helo greeting.'
					return False, IPEMAIL_ERRORTYPE_AUTH
				except smtplib.SMTPException:
					if config.ipemail_debug: 
						print 'No suitable authentication method was found.'
				# RHC / [20060914_1]--

			s.sendmail(self.fromAddress, self.toAddresslist, outerasstring)#outer.as_string()

			del outerasstring
			s.quit()

		# RHC / [20060914_1]
		except smtplib.SMTPRecipientsRefused:
			print 'smtplib.SMTPRecipientsRefused'
			return False, ''
		except smtplib.SMTPHeloError:
			print 'The server didn\'t reply properly to the helo greeting.'
			return False, IPEMAIL_ERRORTYPE_AUTH
		except smtplib.SMTPSenderRefused:
			print 'smtplib.SMTPSenderRefused'
			return False, ''
		except smtplib.SMTPDataError:
			print 'smtplib.SMTPDataError'
			return False, ''
		# RHC / [20060914_1]--
		
#		except smtplib.SMTPConnectError:
#			print 'smtplib.SMTPConnectError'
#			return False, ''
#		except smtplib.SMTPResponseException, e:
#			errcode = getattr(e, 'smtp_code', -1)
#			errmsg = getattr(e, 'smtp_error', 'ignore')
#			print 'smtplib.SMTPResponseException',errcode, errmsg
#			return False, ''
#		except smtplib.SMTPServerDisconnected:
#			print 'smtplib.SMTPServerDisconnected'
#			return False, ''

		except:
			#print 'ipemail send except'
			return False, ''
		return True, ''

def IpEmailSendloop():
	ipemailcomm = IpEmail_Comm()
	ipemailsend = IpEmailSend()
	ipemailcomm.Send_Packet(chr(IPEMAIL_SENDREADY))
	sendinfo = []
	while 1:
		try:
			receive = ipemailcomm.Recv_Packet()

			if IPEMAIL_SENDINFO_HOST <= ord(receive[0]) and \
				ord(receive[0]) <= IPEMAIL_SENDINFO_SMTPPASS:
				sendinfo.append([ord(receive[0]), receive[1:]])
			elif IPEMAIL_SENDSTART == ord(receive[0]):
				ipemailsend.Set_SendMessage(sendinfo)
				sendinfo = []
				sendresult = ipemailsend.Send_Mail()
				if sendresult[0]:
					ipemailcomm.Send_Packet(chr(IPEMAIL_SENDEND)+chr(IPEMAIL_SENDRESULTOK))
				else:
					if IPEMAIL_ERRORTYPE_AUTH == sendresult[1]:
						ipemailcomm.Send_Packet(chr(IPEMAIL_SENDEND)+chr(IPEMAIL_SENDRESULTFAIL_AUTH))
					else:
						ipemailcomm.Send_Packet(chr(IPEMAIL_SENDEND)+chr(IPEMAIL_SENDRESULTFAIL))
		except:
			ipemailcomm.Send_Packet(chr(IPEMAIL_SENDEND)+chr(IPEMAIL_SENDRESULTFAIL))
			print '==================ipemail send except===================='


IpEmailSendloop()