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 _
34 _logger = logging.getLogger('mailgate')
36 class mailgate_thread(osv.osv):
40 _name = 'mailgate.thread'
41 _description = 'Mailgateway Thread'
44 'message_ids': fields.one2many('mailgate.message', 'res_id', 'Messages', readonly=True),
47 def copy(self, cr, uid, id, default=None, context=None):
49 Overrides orm copy method.
50 @param self: the object pointer
51 @param cr: the current row, from the database cursor,
52 @param uid: the current user’s ID for security checks,
53 @param id: Id of mailgate thread
54 @param default: Dictionary of default values for copy.
55 @param context: A standard dictionary for contextual values
67 return super(mailgate_thread, self).copy(cr, uid, id, default, context=context)
69 def message_new(self, cr, uid, msg, context):
70 raise Exception, _('Method is not implemented')
72 def message_update(self, cr, uid, ids, vals={}, msg="", default_act='pending', context={}):
73 raise Exception, _('Method is not implemented')
75 def message_followers(self, cr, uid, ids, context=None):
76 """ Get a list of emails of the people following this thread
79 if isinstance(ids, (str, int, long)):
81 for thread in self.browse(cr, uid, ids, context=context):
83 for message in thread.message_ids:
84 l.append((message.user_id and message.user_id.email) or '')
85 l.append(message.email_from or '')
86 l.append(message.email_cc or '')
90 def msg_send(self, cr, uid, id, *args, **argv):
91 raise Exception, _('Method is not implemented')
93 def history(self, cr, uid, cases, keyword, history=False, subject=None, email=False, details=None, \
94 email_from=False, message_id=False, references=None, attach=None, email_cc=None, \
95 email_bcc=None, email_date=None, context=None):
97 @param self: The object pointer
98 @param cr: the current row, from the database cursor,
99 @param uid: the current user’s ID for security checks,
100 @param cases: a browse record list
101 @param keyword: Case action keyword e.g.: If case is closed "Close" keyword is used
102 @param history: Value True/False, If True it makes entry in case History otherwise in Case Log
103 @param email: Email-To / Recipient address
104 @param email_from: Email From / Sender address if any
105 @param email_cc: Comma-Separated list of Carbon Copy Emails To addresse if any
106 @param email_bcc: Comma-Separated list of Blind Carbon Copy Emails To addresses if any
107 @param email_date: Email Date string if different from now, in server Timezone
108 @param details: Description, Details of case history if any
109 @param atach: Attachment sent in email
110 @param context: A standard dictionary for contextual values"""
116 # The mailgate sends the ids of the cases and not the object list
118 if all(isinstance(case_id, (int, long)) for case_id in cases):
119 cases = self.browse(cr, uid, cases, context=context)
121 att_obj = self.pool.get('ir.attachment')
122 obj = self.pool.get('mailgate.message')
127 attachments.append(att_obj.create(cr, uid, {'name': att[0], 'datas': base64.encodestring(att[1])}))
129 partner_id = hasattr(case, 'partner_id') and (case.partner_id and case.partner_id.id or False) or False
130 if not partner_id and case._name == 'res.partner':
135 'model' : case._name,
136 'partner_id': partner_id,
138 'date': time.strftime('%Y-%m-%d %H:%M:%S'),
139 'message_id': message_id,
140 'description': details or (hasattr(case, 'description') and case.description or False),
141 'attachment_ids': [(6, 0, attachments)]
145 for param in (email, email_cc, email_bcc):
146 if isinstance(param, list):
147 param = ", ".join(param)
150 'name': subject or _('History'),
153 'model' : case._name,
155 'date': email_date or time.strftime('%Y-%m-%d %H:%M:%S'),
156 'description': details or (hasattr(case, 'description') and case.description or False),
158 'email_from': email_from or \
159 (hasattr(case, 'user_id') and case.user_id and case.user_id.address_id and \
160 case.user_id.address_id.email),
161 'email_cc': email_cc,
162 'email_bcc': email_bcc,
163 'partner_id': partner_id,
164 'references': references,
165 'message_id': message_id,
166 'attachment_ids': [(6, 0, attachments)]
168 obj.create(cr, uid, data, context=context)
172 def format_date_tz(date, tz=None):
175 format = tools.DEFAULT_SERVER_DATETIME_FORMAT
176 return tools.server_to_local_timestamp(date, format, format, tz)
178 class mailgate_message(osv.osv):
182 def truncate_data(self, cr, uid, data, context=None):
183 data_list = data and data.split('\n') or []
184 if len(data_list) > 3:
185 res = '\n\t'.join(data_list[:3]) + '...'
187 res = '\n\t'.join(data_list)
190 def _get_display_text(self, cr, uid, ids, name, arg, context=None):
193 tz = context.get('tz')
195 for message in self.browse(cr, uid, ids, context=context):
198 msg_txt += (message.email_from or '/') + _(' wrote on ') + format_date_tz(message.date, tz) + ':\n\t'
199 if message.description:
200 msg_txt += self.truncate_data(cr, uid, message.description, context=context)
202 msg_txt = (message.user_id.name or '/') + _(' on ') + format_date_tz(message.date, tz) + ':\n\t'
203 if message.name == _('Opportunity'):
204 msg_txt += _("Converted to Opportunity")
205 elif message.name == _('Note'):
206 msg_txt = (message.user_id.name or '/') + _(' added note on ') + format_date_tz(message.date, tz) + ':\n\t'
207 msg_txt += self.truncate_data(cr, uid, message.description, context=context)
209 msg_txt += _("Changed Status to: ") + message.name
210 result[message.id] = msg_txt
213 _name = 'mailgate.message'
214 _description = 'Mailgateway Message'
217 'name':fields.text('Subject', readonly=True),
218 'model': fields.char('Object Name', size=128, select=1, readonly=True),
219 'res_id': fields.integer('Resource ID', select=1, readonly=True),
220 'ref_id': fields.char('Reference Id', size=256, readonly=True, help="Message Id in Email Server.", select=True),
221 'date': fields.datetime('Date', readonly=True),
222 'history': fields.boolean('Is History?', readonly=True),
223 'user_id': fields.many2one('res.users', 'User Responsible', readonly=True),
224 'message': fields.text('Description', readonly=True),
225 'email_from': fields.char('From', size=128, help="Email From", readonly=True),
226 'email_to': fields.char('To', help="Email Recipients", size=256, readonly=True),
227 'email_cc': fields.char('Cc', help="Carbon Copy Email Recipients", size=256, readonly=True),
228 'email_bcc': fields.char('Bcc', help='Blind Carbon Copy Email Recipients', size=256, readonly=True),
229 'message_id': fields.char('Message Id', size=1024, readonly=True, help="Message Id on Email.", select=True),
230 'references': fields.text('References', readonly=True, help="References emails."),
231 'description': fields.text('Description', readonly=True),
232 'partner_id': fields.many2one('res.partner', 'Partner', required=False),
233 'attachment_ids': fields.many2many('ir.attachment', 'message_attachment_rel', 'message_id', 'attachment_id', 'Attachments', readonly=True),
234 'display_text': fields.function(_get_display_text, method=True, type='text', size="512", string='Display Text'),
238 cr.execute("""SELECT indexname
240 WHERE indexname = 'mailgate_message_res_id_model_idx'""")
241 if not cr.fetchone():
242 cr.execute("""CREATE INDEX mailgate_message_res_id_model_idx
243 ON mailgate_message (model, res_id)""")
247 class mailgate_tool(osv.osv_memory):
249 _name = 'email.server.tools'
250 _description = "Email Server Tools"
252 def _decode_header(self, text):
253 """Returns unicode() string conversion of the the given encoded smtp header"""
255 text = decode_header(text.replace('\r', ''))
256 return ''.join([tools.ustr(x[0], x[1]) for x in text])
258 def to_email(self,text):
259 return re.findall(r'([^ ,<@]+@[^> ,]+)',text)
261 def history(self, cr, uid, model, res_ids, msg, attach, context=None):
262 """This function creates history for mails fetched
263 @param self: The object pointer
264 @param cr: the current row, from the database cursor,
265 @param uid: the current user’s ID for security checks,
266 @param model: OpenObject Model
267 @param res_ids: Ids of the record of OpenObject model created
268 @param msg: Email details
269 @param attach: Email attachments
271 if isinstance(res_ids, (int, long)):
274 msg_pool = self.pool.get('mailgate.message')
275 for res_id in res_ids:
276 case = self.pool.get(model).browse(cr, uid, res_id, context=context)
277 partner_id = hasattr(case, 'partner_id') and (case.partner_id and case.partner_id.id or False) or False
278 if not partner_id and model == 'res.partner':
281 'name': msg.get('subject', 'No subject'),
282 'date': msg.get('date'),
283 'description': msg.get('body', msg.get('from')),
285 'partner_id': partner_id,
287 'email_cc': msg.get('cc'),
288 'email_from': msg.get('from'),
289 'email_to': msg.get('to'),
290 'message_id': msg.get('message-id'),
291 'references': msg.get('references') or msg.get('in-reply-to'),
294 'attachment_ids': [(6, 0, attach)]
296 msg_pool.create(cr, uid, msg_data, context=context)
299 def email_forward(self, cr, uid, model, res_ids, msg, email_error=False, context=None):
300 """Sends an email to all people following the thread
301 @param res_id: Id of the record of OpenObject model created from the email message
302 @param msg: email.message.Message to forward
303 @param email_error: Default Email address in case of any Problem
305 model_pool = self.pool.get(model)
307 for res in model_pool.browse(cr, uid, res_ids, context=context):
308 message_followers = model_pool.message_followers(cr, uid, [res.id])[res.id]
309 message_followers_emails = self.to_email(','.join(filter(None, message_followers)))
310 message_recipients = self.to_email(','.join(filter(None,
311 [self._decode_header(msg['from']),
312 self._decode_header(msg['to']),
313 self._decode_header(msg['cc'])])))
314 message_forward = [i for i in message_followers_emails if (i and (i not in message_recipients))]
317 # TODO: we need an interface for this for all types of objects, not just leads
318 if hasattr(res, 'section_id'):
320 msg['reply-to'] = res.section_id.reply_to
322 smtp_from = self.to_email(msg['from'])
323 if not tools.misc._email_send(smtp_from, message_forward, msg, openobject_id=res.id) and email_error:
324 subj = msg['subject']
325 del msg['subject'], msg['to'], msg['cc'], msg['bcc']
326 msg['subject'] = '[OpenERP-Forward-Failed] %s' % subj
327 msg['to'] = email_error
328 tools.misc._email_send(smtp_from, self.to_email(email_error), msg, openobject_id=res.id)
330 def process_email(self, cr, uid, model, message, attach=True, context=None):
331 """This function Processes email and create record for given OpenERP model
332 @param self: The object pointer
333 @param cr: the current row, from the database cursor,
334 @param uid: the current user’s ID for security checks,
335 @param model: OpenObject Model
336 @param message: Email details, passed as a string or an xmlrpclib.Binary
337 @param attach: Email attachments
338 @param context: A standard dictionary for contextual values"""
340 # extract message bytes, we are forced to pass the message as binary because
341 # we don't know its encoding until we parse its headers and hence can't
342 # convert it to utf-8 for transport between the mailgate script and here.
343 if isinstance(message, xmlrpclib.Binary):
344 message = str(message.data)
349 model_pool = self.pool.get(model)
352 # Create New Record into particular model
353 def create_record(msg):
355 if hasattr(model_pool, 'message_new'):
356 res_id = model_pool.message_new(cr, uid, msg, context)
359 'name': msg.get('subject'),
360 'email_from': msg.get('from'),
361 'email_cc': msg.get('cc'),
363 'description': msg.get('body'),
366 data.update(self.get_partner(cr, uid, msg.get('from'), context=context))
367 res_id = model_pool.create(cr, uid, data, context=context)
370 for attachment in msg.get('attachments', []):
373 'datas': binascii.b2a_base64(str(attachments.get(attachment))),
374 'datas_fname': attachment,
375 'description': 'Mail attachment',
379 att_ids.append(self.pool.get('ir.attachment').create(cr, uid, data_attach))
381 return res_id, att_ids
383 # Warning: message_from_string doesn't always work correctly on unicode,
384 # we must use utf-8 strings here :-(
385 if isinstance(message, unicode):
386 message = message.encode('utf-8')
387 msg_txt = email.message_from_string(message)
388 message_id = msg_txt.get('message-id', False)
392 # Very unusual situation, be we should be fault-tolerant here
393 message_id = time.time()
394 msg_txt['message-id'] = message_id
395 _logger.info('Message without message-id, generating a random one: %s', message_id)
397 fields = msg_txt.keys()
398 msg['id'] = message_id
399 msg['message-id'] = message_id
401 if 'Subject' in fields:
402 msg['subject'] = self._decode_header(msg_txt.get('Subject'))
404 if 'Content-Type' in fields:
405 msg['content-type'] = msg_txt.get('Content-Type')
408 msg['from'] = self._decode_header(msg_txt.get('From'))
410 if 'Delivered-To' in fields:
411 msg['to'] = self._decode_header(msg_txt.get('Delivered-To'))
414 msg['cc'] = self._decode_header(msg_txt.get('CC'))
416 if 'Reply-to' in fields:
417 msg['reply'] = self._decode_header(msg_txt.get('Reply-To'))
420 msg['date'] = self._decode_header(msg_txt.get('Date'))
422 if 'Content-Transfer-Encoding' in fields:
423 msg['encoding'] = msg_txt.get('Content-Transfer-Encoding')
425 if 'References' in fields:
426 msg['references'] = msg_txt.get('References')
428 if 'In-Reply-To' in fields:
429 msg['in-reply-to'] = msg_txt.get('In-Reply-To')
431 if 'X-Priority' in fields:
432 msg['priority'] = msg_txt.get('X-Priority', '3 (Normal)').split(' ')[0]
434 if not msg_txt.is_multipart() or 'text/plain' in msg.get('Content-Type', ''):
435 encoding = msg_txt.get_content_charset()
436 body = msg_txt.get_payload(decode=True)
437 msg['body'] = tools.ustr(body, encoding)
440 has_plain_text = False
441 if msg_txt.is_multipart() or 'multipart/alternative' in msg.get('content-type', ''):
443 for part in msg_txt.walk():
444 if part.get_content_maintype() == 'multipart':
447 encoding = part.get_content_charset()
448 filename = part.get_filename()
449 if part.get_content_maintype()=='text':
450 content = part.get_payload(decode=True)
452 attachments[filename] = content
453 elif not has_plain_text:
454 # main content parts should have 'text' maintype
455 # and no filename. we ignore the html part if
456 # there is already a plaintext part without filename,
457 # because presumably these are alternatives.
458 content = tools.ustr(content, encoding)
459 if part.get_content_subtype() == 'html':
460 body = tools.ustr(tools.html2plaintext(content))
461 elif part.get_content_subtype() == 'plain':
463 has_plain_text = True
464 elif part.get_content_maintype() in ('application', 'image'):
466 attachments[filename] = part.get_payload(decode=True)
468 res = part.get_payload(decode=True)
469 body += tools.ustr(res, encoding)
472 msg['attachments'] = attachments
476 if msg.get('references') or msg.get('in-reply-to'):
477 references = msg.get('references') or msg.get('in-reply-to')
478 if '\r\n' in references:
479 references = references.split('\r\n')
481 references = references.split(' ')
482 for ref in references:
484 res_id = tools.misc.reference_re.search(ref)
486 res_id = res_id.group(1)
488 res_id = tools.misc.res_re.search(msg['subject'])
490 res_id = res_id.group(1)
493 model_pool = self.pool.get(model)
494 if model_pool.exists(cr, uid, res_id):
495 res_ids.append(res_id)
496 if hasattr(model_pool, 'message_update'):
497 model_pool.message_update(cr, uid, [res_id], {}, msg, context=context)
499 raise NotImplementedError('model %s does not support updating records, mailgate API method message_update() is missing'%model)
502 new_res_id, attachment_ids = create_record(msg)
503 res_ids = [new_res_id]
506 context.update({'model' : model})
507 if hasattr(model_pool, 'history'):
508 model_pool.history(cr, uid, res_ids, _('receive'), history=True,
509 subject = msg.get('subject'),
510 email = msg.get('to'),
511 details = msg.get('body'),
512 email_from = msg.get('from'),
513 email_cc = msg.get('cc'),
514 message_id = msg.get('message-id'),
515 references = msg.get('references', False) or msg.get('in-reply-to', False),
516 attach = attachments.items(),
519 self.history(cr, uid, model, res_ids, msg, attachment_ids, context=context)
520 self.email_forward(cr, uid, model, res_ids, msg_txt)
523 def get_partner(self, cr, uid, from_email, context=None):
524 """This function returns partner Id based on email passed
525 @param self: The object pointer
526 @param cr: the current row, from the database cursor,
527 @param uid: the current user’s ID for security checks
528 @param from_email: email address based on that function will search for the correct
530 address_pool = self.pool.get('res.partner.address')
532 'partner_address_id': False,
535 from_email = self.to_email(from_email)[0]
536 address_ids = address_pool.search(cr, uid, [('email', 'like', from_email)])
538 address = address_pool.browse(cr, uid, address_ids[0])
539 res['partner_address_id'] = address_ids[0]
540 res['partner_id'] = address.partner_id.id