1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>)
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as
9 # published by the Free Software Foundation, either version 3 of the
10 # License, or (at your option) any later version
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>
20 ##############################################################################
22 from osv import osv, fields
27 from email.header import decode_header
30 from tools.translate import _
33 _logger = logging.getLogger('mailgate')
35 class mailgate_thread(osv.osv):
39 _name = 'mailgate.thread'
40 _description = 'Mailgateway Thread'
43 'message_ids': fields.one2many('mailgate.message', 'res_id', 'Messages', domain=[('history', '=', True)]),
44 'log_ids': fields.one2many('mailgate.message', 'res_id', 'Logs', domain=[('history', '=', False)]),
47 def message_new(self, cr, uid, msg, context):
48 raise Exception, _('Method is not implemented')
50 def message_update(self, cr, uid, ids, vals={}, msg="", default_act='pending', context={}):
51 raise Exception, _('Method is not implemented')
53 def message_followers(self, cr, uid, ids, context=None):
54 """ Get a list of emails of the people following this thread
57 if isinstance(ids, (str, int, long)):
59 for thread in self.browse(cr, uid, ids, context=context):
61 for message in thread.message_ids:
62 l.append((message.user_id and message.user_id.email) or '')
63 l.append(message.email_from or '')
64 l.append(message.email_cc or '')
68 def msg_send(self, cr, uid, id, *args, **argv):
69 raise Exception, _('Method is not implemented')
71 def _history(self, cr, uid, cases, keyword, history=False, subject=None, email=False, details=None, \
72 email_from=False, message_id=False, references=None, attach=None, context=None):
74 @param self: The object pointer
75 @param cr: the current row, from the database cursor,
76 @param uid: the current user’s ID for security checks,
77 @param cases: a browse record list
78 @param keyword: Case action keyword e.g.: If case is closed "Close" keyword is used
79 @param history: Value True/False, If True it makes entry in case History otherwise in Case Log
80 @param email: Email address if any
81 @param details: Details of case history if any
82 @param atach: Attachment sent in email
83 @param context: A standard dictionary for contextual values"""
89 # The mailgate sends the ids of the cases and not the object list
91 if all(isinstance(case_id, (int, long)) for case_id in cases):
92 cases = self.browse(cr, uid, cases, context=context)
94 att_obj = self.pool.get('ir.attachment')
95 obj = self.pool.get('mailgate.message')
101 'model' : case._name,
103 'date': time.strftime('%Y-%m-%d %H:%M:%S'),
104 'message_id': message_id,
109 attachments.append(att_obj.create(cr, uid, {'name': att[0], 'datas': base64.encodestring(att[1])}))
112 'name': subject or 'History',
115 'model' : case._name,
117 'date': time.strftime('%Y-%m-%d %H:%M:%S'),
118 'description': details or (hasattr(case, 'description') and case.description or False),
119 'email_to': email or \
120 (hasattr(case, 'user_id') and case.user_id and case.user_id.address_id and \
121 case.user_id.address_id.email) or tools.config.get('email_from', False),
122 'email_from': email_from or \
123 (hasattr(case, 'user_id') and case.user_id and case.user_id.address_id and \
124 case.user_id.address_id.email) or tools.config.get('email_from', False),
125 'partner_id': hasattr(case, 'partner_id') and (case.partner_id and case.partner_id.id or False) or False,
126 'references': references,
127 'message_id': message_id,
128 'attachment_ids': [(6, 0, attachments)]
130 res = obj.create(cr, uid, data, context)
134 class mailgate_message(osv.osv):
138 _name = 'mailgate.message'
139 _description = 'Mailgateway Message'
142 'name':fields.char('Subject', size=128),
143 'model': fields.char('Object Name', size=128),
144 'res_id': fields.integer('Resource ID'),
145 'ref_id': fields.char('Reference Id', size=256, readonly=True, help="Message Id in Email Server.", select=True),
146 'date': fields.datetime('Date'),
147 'history': fields.boolean('Is History?'),
148 'user_id': fields.many2one('res.users', 'User Responsible', readonly=True),
149 'message': fields.text('Description'),
150 'email_from': fields.char('Email From', size=84),
151 'email_to': fields.char('Email To', size=84),
152 'email_cc': fields.char('Email CC', size=84),
153 'email_bcc': fields.char('Email BCC', size=84),
154 'message_id': fields.char('Message Id', size=1024, readonly=True, help="Message Id on Email.", select=True),
155 'references': fields.text('References', readonly=True, help="Referencess emails."),
156 'description': fields.text('Description'),
157 'partner_id': fields.many2one('res.partner', 'Partner', required=False),
158 'attachment_ids': fields.many2many('ir.attachment', 'message_attachment_rel', 'message_id', 'attachment_id', 'Attachments'),
163 class mailgate_tool(osv.osv_memory):
165 _name = 'email.server.tools'
166 _description = "Email Server Tools"
168 def _to_decode(self, s, charsets):
171 for charset in charsets:
174 return s.decode(charset)
177 return s.decode('latin1')
179 def _decode_header(self, text):
181 text = decode_header(text.replace('\r', ''))
182 return ''.join(map(lambda x:self._to_decode(x[0], [x[1]]), text or []))
184 def to_email(self,text):
185 return re.findall(r'([^ ,<@]+@[^> ,]+)',text)
187 def history(self, cr, uid, model, res_ids, msg, attach, context=None):
188 """This function creates history for mails fetched
189 @param self: The object pointer
190 @param cr: the current row, from the database cursor,
191 @param uid: the current user’s ID for security checks,
192 @param model: OpenObject Model
193 @param res_ids: Ids of the record of OpenObject model created
194 @param msg: Email details
195 @param attach: Email attachments
197 if isinstance(res_ids, (int, long)):
200 msg_pool = self.pool.get('mailgate.message')
201 for res_id in res_ids:
203 'name': msg.get('subject', 'No subject'),
204 'date': msg.get('date') ,
205 'description': msg.get('body', msg.get('from')),
208 'email_cc': msg.get('cc'),
209 'email_from': msg.get('from'),
210 'email_to': msg.get('to'),
211 'message_id': msg.get('message-id'),
212 'references': msg.get('references'),
215 'attachment_ids': [(6, 0, attach)]
217 msg_id = msg_pool.create(cr, uid, msg_data, context=context)
220 def email_forward(self, cr, uid, model, res_ids, msg, email_error=False):
221 """Sends an email to all people following the thread
222 @param res_id: Id of the record of OpenObject model created from the Email details
223 @param msg: Email details
224 @param email_error: Default Email address in case of any Problem
226 for res_id in res_ids:
227 history_pool = self.pool.get('mailgate.message')
228 message = email.message_from_string(tools.ustr(msg).encode('utf-8'))
229 encoding = message.get_content_charset()
230 message['body'] = message.get_payload(decode=True)
232 message['body'] = self._to_decode(message['body'], [encoding])
233 subject = message['Subject']
235 from_email = self._decode_header(message['From'])
237 model_pool = self.pool.get(model)
238 message_followers = model_pool.message_followers(cr, uid, [res_id])[res_id]
239 message_followers_emails = self.to_email(','.join(message_followers))
241 message_recipients = self.to_email(','.join([from_email,self._decode_header(message['To']),self._decode_header(message['Cc'])]) )
242 message_forward = [i for i in message_followers_emails if (i and (i not in message_recipients))]
246 res = tools.email_send(from_email, message_forward, subject, body, openobject_id=res_id)
249 temp_msg = '[%s] %s'%(res_id, message['Subject'])
250 del message['Subject']
251 message['Subject'] = '[OpenERP-Error] %s' %(temp_msg)
252 tools.email_send(from_email, email_error, message.get('Subject'), message.get('body'), openobject_id=res_id)
254 def process_email(self, cr, uid, model, message, attach=True, context=None):
255 """This function Processes email and create record for given OpenERP model
256 @param self: The object pointer
257 @param cr: the current row, from the database cursor,
258 @param uid: the current user’s ID for security checks,
259 @param model: OpenObject Model
260 @param message: Email details
261 @param attach: Email attachments
262 @param context: A standard dictionary for contextual values"""
263 model_pool = self.pool.get(model)
267 # Create New Record into particular model
268 def create_record(msg):
269 if hasattr(model_pool, 'message_new'):
270 res_id = model_pool.message_new(cr, uid, msg, context)
273 'name': msg.get('subject'),
274 'email_from': msg.get('from'),
275 'email_cc': msg.get('cc'),
277 'description': msg.get('body'),
280 data.update(self.get_partner(cr, uid, msg.get('from'), context=context))
281 res_id = model_pool.create(cr, uid, data, context=context)
285 for attachment in msg.get('attachments', []):
288 'datas': binascii.b2a_base64(str(attachments.get(attachment))),
289 'datas_fname': attachment,
290 'description': 'Mail attachment',
294 att_ids.append(self.pool.get('ir.attachment').create(cr, uid, data_attach))
298 history_pool = self.pool.get('mailgate.message')
300 # Warning: message_from_string doesn't always work correctly on unicode,
301 # we must use utf-8 strings here :-(
302 msg_txt = email.message_from_string(tools.ustr(message).encode('utf-8'))
303 message_id = msg_txt.get('Message-ID', False)
307 # Very unusual situation, be we should be fault-tolerant here
308 message_id = time.time()
309 msg_txt['Message-ID'] = message_id
310 _logger.info('Message without message-id, generating a random one: %s', message_id)
312 fields = msg_txt.keys()
313 msg['id'] = message_id
314 msg['message-id'] = message_id
316 if 'Subject' in fields:
317 msg['subject'] = self._decode_header(msg_txt.get('Subject'))
319 if 'Content-Type' in fields:
320 msg['content-type'] = msg_txt.get('Content-Type')
323 msg['from'] = self._decode_header(msg_txt.get('From'))
325 if 'Delivered-To' in fields:
326 msg['to'] = self._decode_header(msg_txt.get('Delivered-To'))
329 msg['cc'] = self._decode_header(msg_txt.get('Cc'))
331 if 'Reply-To' in fields:
332 msg['reply'] = self._decode_header(msg_txt.get('Reply-To'))
335 msg['date'] = msg_txt.get('Date')
337 if 'Content-Transfer-Encoding' in fields:
338 msg['encoding'] = msg_txt.get('Content-Transfer-Encoding')
340 if 'References' in fields:
341 msg['references'] = msg_txt.get('References')
343 if 'X-Priority' in fields:
344 msg['priority'] = msg_txt.get('X-priority', '3 (Normal)').split(' ')[0]
346 if not msg_txt.is_multipart() or 'text/plain' in msg.get('content-type', ''):
347 encoding = msg_txt.get_content_charset()
348 msg['body'] = msg_txt.get_payload(decode=True)
350 msg['body'] = tools.ustr(msg['body'])
353 if msg_txt.is_multipart() or 'multipart/alternative' in msg.get('content-type', ''):
356 for part in msg_txt.walk():
357 if part.get_content_maintype() == 'multipart':
360 encoding = part.get_content_charset()
362 if part.get_content_maintype()=='text':
363 content = part.get_payload(decode=True)
364 filename = part.get_filename()
366 attachments[filename] = content
369 content = unicode(content, encoding)
370 if part.get_content_subtype() == 'html':
371 body = tools.html2plaintext(content)
372 elif part.get_content_subtype() == 'plain':
374 elif part.get_content_maintype()=='application' or part.get_content_maintype()=='image' or part.get_content_maintype()=='text':
375 filename = part.get_filename();
377 attachments[filename] = part.get_payload(decode=True)
379 res = part.get_payload(decode=True)
381 res = tools.ustr(res)
385 msg['attachments'] = attachments
388 if msg.get('references'):
389 references = msg.get('references')
390 if '\r\n' in references:
391 references = msg.get('references').split('\r\n')
393 references = msg.get('references').split(' ')
394 for ref in references:
396 res_id = tools.misc.reference_re.search(ref)
398 res_id = res_id.group(1)
400 res_id = tools.misc.res_re.search(msg['subject'])
402 res_id = res_id.group(1)
405 res_ids.append(res_id)
406 model_pool = self.pool.get(model)
409 if hasattr(model_pool, 'message_update'):
410 model_pool.message_update(cr, uid, [res_id], vals, msg, context=context)
413 new_res_id = create_record(msg)
414 res_ids = [new_res_id]
416 context.update({'model' : model})
417 if hasattr(model_pool, '_history'):
418 model_pool._history(cr, uid, res_ids, _('Receive'), history=True,
419 subject = msg.get('subject'),
420 email = msg.get('to'),
421 details = msg.get('body'),
422 email_from = msg.get('from'),
423 message_id = msg.get('message-id'),
424 references = msg.get('references', False),
425 attach = msg.get('attachments', {}).items(),
428 self.history(cr, uid, model, res_ids, msg, att_ids, context=context)
429 self.email_forward(cr, uid, model, res_ids, message)
432 def get_partner(self, cr, uid, from_email, context=None):
433 """This function returns partner Id based on email passed
434 @param self: The object pointer
435 @param cr: the current row, from the database cursor,
436 @param uid: the current user’s ID for security checks
437 @param from_email: email address based on that function will search for the correct
439 address_pool = self.pool.get('res.partner.address')
441 'partner_address_id': False,
444 from_email = self.to_email(from_email)[0]
445 address_ids = address_pool.search(cr, uid, [('email', '=', from_email)])
447 address = address_pool.browse(cr, uid, address_ids[0])
448 res['partner_address_id'] = address_ids[0]
449 res['partner_id'] = address.partner_id.id