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 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, email_cc=None, \
73 email_bcc=None, email_date=None, context=None):
75 @param self: The object pointer
76 @param cr: the current row, from the database cursor,
77 @param uid: the current user’s ID for security checks,
78 @param cases: a browse record list
79 @param keyword: Case action keyword e.g.: If case is closed "Close" keyword is used
80 @param history: Value True/False, If True it makes entry in case History otherwise in Case Log
81 @param email: Email-To / Recipient address
82 @param email_from: Email From / Sender address if any
83 @param email_cc: Comma-Separated list of Carbon Copy Emails To addresse if any
84 @param email_bcc: Comma-Separated list of Blind Carbon Copy Emails To addresses if any
85 @param email_date: Email Date string if different from now, in server Timezone
86 @param details: Description, Ddtails of case history if any
87 @param atach: Attachment sent in email
88 @param context: A standard dictionary for contextual values"""
94 # The mailgate sends the ids of the cases and not the object list
96 if all(isinstance(case_id, (int, long)) for case_id in cases):
97 cases = self.browse(cr, uid, cases, context=context)
99 att_obj = self.pool.get('ir.attachment')
100 obj = self.pool.get('mailgate.message')
106 'model' : case._name,
108 'date': time.strftime('%Y-%m-%d %H:%M:%S'),
109 'message_id': message_id,
114 attachments.append(att_obj.create(cr, uid, {'name': att[0], 'datas': base64.encodestring(att[1])}))
116 for param in (email, email_cc, email_bcc):
117 if isinstance(param, list):
118 param = ", ".join(param)
121 'name': subject or 'History',
124 'model' : case._name,
126 'date': email_date or time.strftime('%Y-%m-%d %H:%M:%S'),
127 'description': details or (hasattr(case, 'description') and case.description or False),
129 'email_from': email_from or \
130 (hasattr(case, 'user_id') and case.user_id and case.user_id.address_id and \
131 case.user_id.address_id.email),
132 'email_cc': email_cc,
133 'email_bcc': email_bcc,
134 'partner_id': hasattr(case, 'partner_id') and (case.partner_id and case.partner_id.id or False) or False,
135 'references': references,
136 'message_id': message_id,
137 'attachment_ids': [(6, 0, attachments)]
139 obj.create(cr, uid, data, context=context)
143 class mailgate_message(osv.osv):
147 def _get_display_text(self, cr, uid, ids, name, arg, context=None):
149 for message in self.browse(cr, uid, ids, context=context):
152 msg_txt += (message.email_from or '/') + ' wrote on ' + message.date + ':\n\t'
153 msg_txt += '\n\t'.join(message.description.split('\n')[:3]) + '...'
155 msg_txt = (message.user_id.name or '/') + ' on ' + message.date + ':\n\t'
156 if message.name == 'Opportunity':
157 msg_txt += "Converted to Opportunity"
159 msg_txt += "Changed Status to: " + message.name
160 result[message.id] = msg_txt
163 _name = 'mailgate.message'
164 _description = 'Mailgateway Message'
167 'name':fields.text('Subject', readonly=True),
168 'model': fields.char('Object Name', size=128, select=1, readonly=True),
169 'res_id': fields.integer('Resource ID', select=1, readonly=True),
170 'ref_id': fields.char('Reference Id', size=256, readonly=True, help="Message Id in Email Server.", select=True),
171 'date': fields.datetime('Date', readonly=True),
172 'history': fields.boolean('Is History?', readonly=True),
173 'user_id': fields.many2one('res.users', 'User Responsible', readonly=True),
174 'message': fields.text('Description', readonly=True),
175 'email_from': fields.char('From', size=128, help="Email From", readonly=True),
176 'email_to': fields.char('To', help="Email Recipients", size=256, readonly=True),
177 'email_cc': fields.char('Cc', help="Carbon Copy Email Recipients", size=256, readonly=True),
178 'email_bcc': fields.char('Bcc', help='Blind Carbon Copy Email Recipients', size=256, readonly=True),
179 'message_id': fields.char('Message Id', size=1024, readonly=True, help="Message Id on Email.", select=True),
180 'references': fields.text('References', readonly=True, help="References emails."),
181 'description': fields.text('Description', readonly=True),
182 'partner_id': fields.many2one('res.partner', 'Partner', required=False),
183 'attachment_ids': fields.many2many('ir.attachment', 'message_attachment_rel', 'message_id', 'attachment_id', 'Attachments', readonly=True),
184 'display_text': fields.function(_get_display_text, method=True, type='text', size="512", string='Display Text'),
188 cr.execute("""SELECT indexname
190 WHERE indexname = 'mailgate_message_res_id_model_idx'""")
191 if not cr.fetchone():
192 cr.execute("""CREATE INDEX mailgate_message_res_id_model_idx
193 ON mailgate_message (model, res_id)""")
197 class mailgate_tool(osv.osv_memory):
199 _name = 'email.server.tools'
200 _description = "Email Server Tools"
202 def _decode_header(self, text):
203 """Returns unicode() string conversion of the the given encoded smtp header"""
205 text = decode_header(text.replace('\r', ''))
206 return ''.join([tools.ustr(x[0], x[1]) for x in text])
208 def to_email(self,text):
209 return re.findall(r'([^ ,<@]+@[^> ,]+)',text)
211 def history(self, cr, uid, model, res_ids, msg, attach, context=None):
212 """This function creates history for mails fetched
213 @param self: The object pointer
214 @param cr: the current row, from the database cursor,
215 @param uid: the current user’s ID for security checks,
216 @param model: OpenObject Model
217 @param res_ids: Ids of the record of OpenObject model created
218 @param msg: Email details
219 @param attach: Email attachments
221 if isinstance(res_ids, (int, long)):
224 msg_pool = self.pool.get('mailgate.message')
225 for res_id in res_ids:
227 'name': msg.get('subject', 'No subject'),
228 'date': msg.get('date') ,
229 'description': msg.get('body', msg.get('from')),
232 'email_cc': msg.get('cc'),
233 'email_from': msg.get('from'),
234 'email_to': msg.get('to'),
235 'message_id': msg.get('message-id'),
236 'references': msg.get('references'),
239 'attachment_ids': [(6, 0, attach)]
241 msg_pool.create(cr, uid, msg_data, context=context)
244 def email_forward(self, cr, uid, model, res_ids, msg, email_error=False, context=None):
245 """Sends an email to all people following the thread
246 @param res_id: Id of the record of OpenObject model created from the email message
247 @param msg: email.message.Message to forward
248 @param email_error: Default Email address in case of any Problem
250 model_pool = self.pool.get(model)
252 for res in model_pool.browse(cr, uid, res_ids, context=context):
253 message_followers = model_pool.message_followers(cr, uid, [res.id])[res.id]
254 message_followers_emails = self.to_email(','.join(message_followers))
255 message_recipients = self.to_email(','.join(filter(None,
256 [self._decode_header(msg['from']),
257 self._decode_header(msg['to']),
258 self._decode_header(msg['cc'])])))
259 message_forward = [i for i in message_followers_emails if (i and (i not in message_recipients))]
262 # TODO: we need an interface for this for all types of objects, not just leads
263 if hasattr(res, 'section_id'):
265 msg['reply-to'] = res.section_id.reply_to
267 smtp_from = self.to_email(msg['from'])
268 if not tools.misc._email_send(smtp_from, message_forward, msg, openobject_id=res.id) and email_error:
269 subj = msg['subject']
270 del msg['subject'], msg['to'], msg['cc'], msg['bcc']
271 msg['subject'] = '[OpenERP-Forward-Failed] %s' % subj
272 msg['to'] = email_error
273 tools.misc._email_send(smtp_from, self.to_email(email_error), msg, openobject_id=res.id)
275 def process_email(self, cr, uid, model, message, attach=True, context=None):
276 """This function Processes email and create record for given OpenERP model
277 @param self: The object pointer
278 @param cr: the current row, from the database cursor,
279 @param uid: the current user’s ID for security checks,
280 @param model: OpenObject Model
281 @param message: Email details, passed as a string or an xmlrpclib.Binary
282 @param attach: Email attachments
283 @param context: A standard dictionary for contextual values"""
285 # extract message bytes, we are forced to pass the message as binary because
286 # we don't know its encoding until we parse its headers and hence can't
287 # convert it to utf-8 for transport between the mailgate script and here.
288 if isinstance(message, xmlrpclib.Binary):
289 message = str(message.data)
294 model_pool = self.pool.get(model)
297 # Create New Record into particular model
298 def create_record(msg):
300 if hasattr(model_pool, 'message_new'):
301 res_id = model_pool.message_new(cr, uid, msg, context)
304 'name': msg.get('subject'),
305 'email_from': msg.get('from'),
306 'email_cc': msg.get('cc'),
308 'description': msg.get('body'),
311 data.update(self.get_partner(cr, uid, msg.get('from'), context=context))
312 res_id = model_pool.create(cr, uid, data, context=context)
315 for attachment in msg.get('attachments', []):
318 'datas': binascii.b2a_base64(str(attachments.get(attachment))),
319 'datas_fname': attachment,
320 'description': 'Mail attachment',
324 att_ids.append(self.pool.get('ir.attachment').create(cr, uid, data_attach))
326 return res_id, att_ids
328 # Warning: message_from_string doesn't always work correctly on unicode,
329 # we must use utf-8 strings here :-(
330 if isinstance(message, unicode):
331 message = message.encode('utf-8')
332 msg_txt = email.message_from_string(message)
333 message_id = msg_txt.get('message-id', False)
337 # Very unusual situation, be we should be fault-tolerant here
338 message_id = time.time()
339 msg_txt['message-id'] = message_id
340 _logger.info('Message without message-id, generating a random one: %s', message_id)
342 fields = msg_txt.keys()
343 msg['id'] = message_id
344 msg['message-id'] = message_id
346 if 'Subject' in fields:
347 msg['subject'] = self._decode_header(msg_txt.get('Subject'))
349 if 'Content-Type' in fields:
350 msg['content-type'] = msg_txt.get('Content-Type')
353 msg['from'] = self._decode_header(msg_txt.get('From'))
355 if 'Delivered-To' in fields:
356 msg['to'] = self._decode_header(msg_txt.get('Delivered-To'))
359 msg['cc'] = self._decode_header(msg_txt.get('CC'))
361 if 'Reply-to' in fields:
362 msg['reply'] = self._decode_header(msg_txt.get('Reply-To'))
365 msg['date'] = self._decode_header(msg_txt.get('Date'))
367 if 'Content-Transfer-Encoding' in fields:
368 msg['encoding'] = msg_txt.get('Content-Transfer-Encoding')
370 if 'References' in fields:
371 msg['references'] = msg_txt.get('References')
373 if 'X-Priority' in fields:
374 msg['priority'] = msg_txt.get('X-Priority', '3 (Normal)').split(' ')[0]
376 if not msg_txt.is_multipart() or 'text/plain' in msg.get('Content-Type', ''):
377 encoding = msg_txt.get_content_charset()
378 body = msg_txt.get_payload(decode=True)
379 msg['body'] = tools.ustr(body, encoding)
382 has_plain_text = False
383 if msg_txt.is_multipart() or 'multipart/alternative' in msg.get('content-type', ''):
385 for part in msg_txt.walk():
386 if part.get_content_maintype() == 'multipart':
389 encoding = part.get_content_charset()
390 filename = part.get_filename()
391 if part.get_content_maintype()=='text':
392 content = part.get_payload(decode=True)
394 attachments[filename] = content
395 elif not has_plain_text:
396 # main content parts should have 'text' maintype
397 # and no filename. we ignore the html part if
398 # there is already a plaintext part without filename,
399 # because presumably these are alternatives.
400 content = tools.ustr(content, encoding)
401 if part.get_content_subtype() == 'html':
402 body = tools.ustr(tools.html2plaintext(content))
403 elif part.get_content_subtype() == 'plain':
405 has_plain_text = True
406 elif part.get_content_maintype() in ('application', 'image'):
408 attachments[filename] = part.get_payload(decode=True)
410 res = part.get_payload(decode=True)
411 body += tools.ustr(res, encoding)
414 msg['attachments'] = attachments
418 if msg.get('references'):
419 references = msg.get('references')
420 if '\r\n' in references:
421 references = msg.get('references').split('\r\n')
423 references = msg.get('references').split(' ')
424 for ref in references:
426 res_id = tools.misc.reference_re.search(ref)
428 res_id = res_id.group(1)
430 res_id = tools.misc.res_re.search(msg['subject'])
432 res_id = res_id.group(1)
435 model_pool = self.pool.get(model)
436 if model_pool.exists(cr, uid, res_id):
437 res_ids.append(res_id)
438 if hasattr(model_pool, 'message_update'):
439 model_pool.message_update(cr, uid, [res_id], {}, msg, context=context)
441 raise NotImplementedError('model %s does not support updating records, mailgate API method message_update() is missing'%model)
444 new_res_id, attachment_ids = create_record(msg)
445 res_ids = [new_res_id]
448 context.update({'model' : model})
449 if hasattr(model_pool, 'history'):
450 model_pool.history(cr, uid, res_ids, _('receive'), history=True,
451 subject = msg.get('subject'),
452 email = msg.get('to'),
453 details = msg.get('body'),
454 email_from = msg.get('from'),
455 email_cc = msg.get('cc'),
456 message_id = msg.get('message-id'),
457 references = msg.get('references', False),
458 attach = attachments.items(),
461 self.history(cr, uid, model, res_ids, msg, attachment_ids, context=context)
462 self.email_forward(cr, uid, model, res_ids, msg_txt)
465 def get_partner(self, cr, uid, from_email, context=None):
466 """This function returns partner Id based on email passed
467 @param self: The object pointer
468 @param cr: the current row, from the database cursor,
469 @param uid: the current user’s ID for security checks
470 @param from_email: email address based on that function will search for the correct
472 address_pool = self.pool.get('res.partner.address')
474 'partner_address_id': False,
477 from_email = self.to_email(from_email)[0]
478 address_ids = address_pool.search(cr, uid, [('email', '=', from_email)])
480 address = address_pool.browse(cr, uid, address_ids[0])
481 res['partner_address_id'] = address_ids[0]
482 res['partner_id'] = address.partner_id.id