mailgate, implement email_send, call it from process_email, rename emails_get to message_followers and factorize it

bzr revid: al@openerp.com-20100625220247-r2svcopmhiwpflgg
This commit is contained in:
Antony Lesuisse 2010-06-25 22:02:47 +00:00
parent 6505388521
commit a2175919f1
6 changed files with 47 additions and 161 deletions

View File

@ -331,37 +331,6 @@ and users"),
return res
def emails_get(self, cr, uid, ids, context=None):
"""
Get Emails
@param self: The object pointer
@param cr: the current row, from the database cursor,
@param uid: the current users ID for security checks,
@param ids: List of emails IDs
@param context: A standard dictionary for contextual values
"""
res = {}
if isinstance(ids, (str, int, long)):
select = [long(ids)]
else:
select = ids
for thread in self.browse(cr, uid, select, context=context):
values = collections.defaultdict(set)
for message in thread.message_ids:
user_email = (message.user_id and message.user_id.address_id and message.user_id.address_id.email) or False
values['user_email'].add(user_email)
values['email_from'].add(message.email_from)
values['email_cc'].add(message.email_cc or False)
values['priority'] = thread.priority
res[thread.id] = dict((key,list(values[key])) for key, value in values.iteritems())
return res
def msg_send(self, cr, uid, id, *args, **argv):
""" Send The Message

View File

@ -327,37 +327,6 @@ class hr_applicant(osv.osv, crm.crm_case):
res = self.write(cr, uid, ids, vals)
return res
def emails_get(self, cr, uid, ids, context=None):
"""
Get Emails
@param self: The object pointer
@param cr: the current row, from the database cursor,
@param uid: the current users ID for security checks,
@param ids: List of emails IDs
@param context: A standard dictionary for contextual values
"""
res = {}
if isinstance(ids, (str, int, long)):
select = [long(ids)]
else:
select = ids
for thread in self.browse(cr, uid, select, context=context):
values = collections.defaultdict(set)
for message in thread.message_ids:
user_email = (message.user_id and message.user_id.address_id and message.user_id.address_id.email) or False
values['user_email'].add(user_email)
values['email_from'].add(message.email_from)
values['email_cc'].add(message.email_cc or False)
values['priority'] = thread.priority
res[thread.id] = dict((key,list(values[key])) for key, value in values.iteritems())
return res
def msg_send(self, cr, uid, id, *args, **argv):
""" Send The Message

View File

@ -50,8 +50,20 @@ class mailgate_thread(osv.osv):
def message_update(self, cr, uid, ids, vals={}, msg="", default_act='pending', context={}):
raise Exception, _('Method is not implemented')
def emails_get(self, cr, uid, ids, context=None):
raise Exception, _('Method is not implemented')
def message_followers(self, cr, uid, ids, context=None):
""" Get a list of emails of the people following this thread
"""
res = {}
if isinstance(ids, (str, int, long)):
ids = [long(ids)]
for thread in self.browse(cr, uid, ids, context=context):
l=[]
for message in thread.message_ids:
l.append((message.user_id and message.user_id.email) or '')
l.append(message.email_from or '')
l.append(message.email_cc or '')
res[thread.id] = l
return res
def msg_send(self, cr, uid, id, *args, **argv):
raise Exception, _('Method is not implemented')
@ -169,16 +181,8 @@ class mailgate_tool(osv.osv_memory):
text = decode_header(text.replace('\r', ''))
return ''.join(map(lambda x:self._to_decode(x[0], [x[1]]), text or []))
def to_email(self, text):
_email = re.compile(r'.*<.*@.*\..*>', re.UNICODE)
def record(path):
eml = path.group()
index = eml.index('<')
eml = eml[index:-1].replace('<', '').replace('>', '')
return eml
bits = _email.sub(record, text)
return bits
def to_email(self,text):
return re.findall(r'([^ ,<@]+@[^> ,]+)',text)
def history(self, cr, uid, model, res_ids, msg, attach, context=None):
"""This function creates history for mails fetched
@ -213,58 +217,39 @@ class mailgate_tool(osv.osv_memory):
msg_id = msg_pool.create(cr, uid, msg_data, context=context)
return True
def email_send(self, cr, uid, model, res_id, msg, from_email=False, email_default=False):
"""This function Sends return email on submission of Fetched email in OpenERP database
@param self: The object pointer
@param cr: the current row, from the database cursor,
@param uid: the current users ID for security checks,
@param model: OpenObject Model
def email_forward(self, cr, uid, model, res_ids, msg, email_error=False):
"""Sends an email to all people following the thread
@param res_id: Id of the record of OpenObject model created from the Email details
@param msg: Email details
@param email_default: Default Email address in case of any Problem
@param email_error: Default Email address in case of any Problem
"""
history_pool = self.pool.get('mailgate.message')
model_pool = self.pool.get(model)
from_email = from_email or tools.config.get('email_from', None)
message = email.message_from_string(tools.ustr(msg).encode('utf-8'))
subject = message['Subject']
for res_id in res_ids:
history_pool = self.pool.get('mailgate.message')
message = email.message_from_string(tools.ustr(msg).encode('utf-8'))
encoding = message.get_content_charset()
message['body'] = message.get_payload(decode=True)
if encoding:
message['body'] = self._to_decode(message['body'], [encoding])
subject = message['Subject']
values = {}
if hasattr(model_pool, 'emails_get'):
values = model_pool.emails_get(cr, uid, [res_id])
emails = values.get(res_id, {})
from_email = self._decode_header(message['From'])
priority = emails.get('priority', [3])[0]
em = emails['user_email'] + emails['email_from'] + emails['email_cc']
msg_mails = map(self.to_email, filter(None, em))
model_pool = self.pool.get(model)
message_followers = model_pool.message_followers(cr, uid, [res_id])[res_id]
message_followers_emails = self.to_email(','.join(message_followers))
encoding = message.get_content_charset()
message['body'] = message.get_payload(decode=True)
if encoding:
message['body'] = self._to_decode(message['body'], [encoding])
message_recipients = self.to_email(','.join([from_email,self._decode_header(message['To']),self._decode_header(message['Cc'])]) )
message_forward = [i for i in message_followers_emails if (i and (i not in message_recipients))]
from_mail = self._decode_header(message['From'])
body = _("""
Hello %s,""" % (from_mail))
body += _("""
Your Request ID: %s""") % (res_id)
body += _("""
Thanks
-------- Original Message --------
%s
""") % (self._to_decode(message['body'], [encoding]))
res = None
try:
res = tools.email_send(from_email, msg_mails, subject, body, openobject_id=res_id)
except Exception, e:
if email_default:
temp_msg = '[%s] %s'%(res_id, message['Subject'])
del message['Subject']
message['Subject'] = '[OpenERP-FetchError] %s' %(temp_msg)
tools.email_send(from_email, email_default, message.get('Subject'), message.get('body'), openobject_id=res_id)
return res
res = None
try:
res = tools.email_send(from_email, message_forward, subject, body, openobject_id=res_id)
except Exception, e:
if email_error:
temp_msg = '[%s] %s'%(res_id, message['Subject'])
del message['Subject']
message['Subject'] = '[OpenERP-Error] %s' %(temp_msg)
tools.email_send(from_email, email_error, message.get('Subject'), message.get('body'), openobject_id=res_id)
def process_email(self, cr, uid, model, message, attach=True, context=None):
"""This function Processes email and create record for given OpenERP model
@ -394,7 +379,6 @@ Thanks
res = part.get_payload(decode=True)
if encoding:
res = tools.ustr(res)
body += res
msg['body'] = body
@ -442,6 +426,7 @@ Thanks
context = context)
else:
self.history(cr, uid, model, res_ids, msg, att_ids, context=context)
self.email_forward(cr, uid, model, res_ids, message)
return new_res_id
def get_partner(self, cr, uid, from_email, context=None):
@ -456,7 +441,7 @@ Thanks
'partner_address_id': False,
'partner_id': False
}
from_email = self.to_email(from_email)
from_email = self.to_email(from_email)[0]
address_ids = address_pool.search(cr, uid, [('email', '=', from_email)])
if address_ids:
address = address_pool.browse(cr, uid, address_ids[0])

View File

@ -38,7 +38,7 @@ class rpc_proxy(object):
return self.rpc.execute(self.dbname, self.user_id, self.passwd, *request, **kwargs)
class email_parser(object):
def __init__(self, uid, password, model, email, email_default, dbname, host, port):
def __init__(self, uid, password, model, email_default, dbname, host, port):
self.rpc = rpc_proxy(uid, password, host=host, port=port, dbname=dbname)
try:
self.model_id = int(model)
@ -46,7 +46,6 @@ class email_parser(object):
except:
self.model_id = self.rpc('ir.model', 'search', [('model', '=', model)])[0]
self.model = str(model)
self.email = email
self.email_default = email_default
@ -59,11 +58,6 @@ class email_parser(object):
logger.debug('Source of the mail that failed to parse:', message)
res_id = False
# Reply mail
if res_id:
self.rpc('email.server.tools', 'email_send', self.model, res_id, message, self.email, self.email_default)
return res_id
if __name__ == '__main__':
parser = optparse.OptionParser(usage='usage: %prog [options]', version='%prog v1.0')
group = optparse.OptionGroup(parser, "Note",
@ -72,7 +66,6 @@ if __name__ == '__main__':
parser.add_option_group(group)
parser.add_option("-u", "--user", dest="userid", help="ID of the user in Open ERP", default=1, type='int')
parser.add_option("-p", "--password", dest="password", help="Password of the user in Open ERP", default='admin')
parser.add_option("-e", "--email", dest="email", help="Email address used in the From field of outgoing messages")
parser.add_option("-o", "--model", dest="model", help="Name or ID of crm model", default="crm.lead")
parser.add_option("-m", "--default", dest="default", help="Default eMail in case of any trouble.", default=None)
parser.add_option("-d", "--dbname", dest="dbname", help="Database name (default: terp)", default='terp')
@ -83,7 +76,7 @@ if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(levelname)s %(message)s")
parser = email_parser(options.userid, options.password, options.model, options.email, options.default, dbname=options.dbname, host=options.host, port=options.port)
parser = email_parser(options.userid, options.password, options.model, options.default, dbname=options.dbname, host=options.host, port=options.port)
msg_txt = sys.stdin.read()

View File

@ -77,7 +77,7 @@ class project_tasks(osv.osv):
getattr(self,act)(cr, uid, [id])
return True
def emails_get(self, cr, uid, ids, context={}):
def message_followers(self, cr, uid, ids, context={}):
res = []
if isinstance(ids, (str, int, long)):
select = [ids]

View File

@ -385,36 +385,6 @@ class project_issue(osv.osv, crm.crm_case):
res = self.write(cr, uid, ids, vals)
return res
def emails_get(self, cr, uid, ids, context=None):
"""
Get Emails
@param self: The object pointer
@param cr: the current row, from the database cursor,
@param uid: the current users ID for security checks,
@param ids: List of emails IDs
@param context: A standard dictionary for contextual values
"""
res = {}
if isinstance(ids, (str, int, long)):
select = [long(ids)]
else:
select = ids
for thread in self.browse(cr, uid, select, context=context):
values = collections.defaultdict(set)
for message in thread.message_ids:
user_email = (message.user_id and message.user_id.address_id and message.user_id.address_id.email) or False
values['user_email'].add(user_email)
values['email_from'].add(message.email_from)
values['email_cc'].add(message.email_cc or False)
values['priority'] = thread.priority
res[thread.id] = dict((key,list(values[key])) for key, value in values.iteritems())
return res
def msg_send(self, cr, uid, id, *args, **argv):