[FIX]: mail_gateway: Problem of encoding in send mail
[odoo/odoo.git] / addons / mail_gateway / mail_gateway.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>)
6 #
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
11 #
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
16 #
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/>
19 #
20 ##############################################################################
21
22 from osv import osv, fields
23 import time
24 import tools
25 import binascii
26 import email
27 from email.header import decode_header
28 import base64
29 import re
30 from tools.translate import _
31 import logging
32
33 _logger = logging.getLogger('mailgate')
34
35 class mailgate_thread(osv.osv):
36     '''
37     Mailgateway Thread
38     '''
39     _name = 'mailgate.thread'
40     _description = 'Mailgateway Thread'
41
42     _columns = {
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)]),
45     }
46
47     def message_new(self, cr, uid, msg, context):
48         raise Exception, _('Method is not implemented')
49
50     def message_update(self, cr, uid, ids, vals={}, msg="", default_act='pending', context={}):
51         raise Exception, _('Method is not implemented')
52
53     def emails_get(self, cr, uid, ids, context=None):
54         raise Exception, _('Method is not implemented')
55
56     def msg_send(self, cr, uid, id, *args, **argv):
57         raise Exception, _('Method is not implemented')
58
59     def _history(self, cr, uid, cases, keyword, history=False, subject=None, email=False, details=None, \
60                     email_from=False, message_id=False, references=None, attach=None, context=None):
61         """
62         @param self: The object pointer
63         @param cr: the current row, from the database cursor,
64         @param uid: the current user’s ID for security checks,
65         @param cases: a browse record list
66         @param keyword: Case action keyword e.g.: If case is closed "Close" keyword is used
67         @param history: Value True/False, If True it makes entry in case History otherwise in Case Log
68         @param email: Email address if any
69         @param details: Details of case history if any 
70         @param atach: Attachment sent in email
71         @param context: A standard dictionary for contextual values"""
72         if context is None:
73             context = {}
74         if attach is None:
75             attach = []
76
77         # The mailgate sends the ids of the cases and not the object list
78
79         if all(isinstance(case_id, (int, long)) for case_id in cases):
80             cases = self.browse(cr, uid, cases, context=context)
81
82         att_obj = self.pool.get('ir.attachment')
83         obj = self.pool.get('mailgate.message')
84
85         for case in cases:
86             data = {
87                 'name': keyword, 
88                 'user_id': uid, 
89                 'model' : case._name, 
90                 'res_id': case.id, 
91                 'date': time.strftime('%Y-%m-%d %H:%M:%S'), 
92                 'message_id': message_id, 
93             }
94             attachments = []
95             if history:
96                 for att in attach:
97                     attachments.append(att_obj.create(cr, uid, {'name': att[0], 'datas': base64.encodestring(att[1])}))
98
99                 data = {
100                     'name': subject or 'History', 
101                     'history': True, 
102                     'user_id': uid, 
103                     'model' : case._name, 
104                     'res_id': case.id,
105                     'date': time.strftime('%Y-%m-%d %H:%M:%S'), 
106                     'description': details or (hasattr(case, 'description') and case.description or False), 
107                     'email_to': email or \
108                         (hasattr(case, 'user_id') and case.user_id and case.user_id.address_id and \
109                          case.user_id.address_id.email) or tools.config.get('email_from', False), 
110                     'email_from': email_from or \
111                         (hasattr(case, 'user_id') and case.user_id and case.user_id.address_id and \
112                          case.user_id.address_id.email) or tools.config.get('email_from', False), 
113                     'partner_id': hasattr(case, 'partner_id') and (case.partner_id and case.partner_id.id or False) or False, 
114                     'references': references, 
115                     'message_id': message_id, 
116                     'attachment_ids': [(6, 0, attachments)]
117                 }
118             res = obj.create(cr, uid, data, context)
119         return True
120 mailgate_thread()
121
122 class mailgate_message(osv.osv):
123     '''
124     Mailgateway Message
125     '''
126     _name = 'mailgate.message'
127     _description = 'Mailgateway Message'
128     _order = 'id desc'
129     _columns = {
130         'name':fields.char('Message', size=64), 
131         'model': fields.char('Object Name', size=128), 
132         'res_id': fields.integer('Resource ID'),
133         'ref_id': fields.char('Reference Id', size=256, readonly=True, help="Message Id in Email Server.", select=True),
134         'date': fields.datetime('Date'), 
135         'history': fields.boolean('Is History?'),
136         'user_id': fields.many2one('res.users', 'User Responsible', readonly=True), 
137         'message': fields.text('Description'), 
138         'email_from': fields.char('Email From', size=84), 
139         'email_to': fields.char('Email To', size=84), 
140         'email_cc': fields.char('Email CC', size=84), 
141         'email_bcc': fields.char('Email BCC', size=84), 
142         'message_id': fields.char('Message Id', size=1024, readonly=True, help="Message Id on Email.", select=True),
143         'references': fields.text('References', readonly=True, help="Referencess emails."),
144         'description': fields.text('Description'), 
145         'partner_id': fields.many2one('res.partner', 'Partner', required=False), 
146         'attachment_ids': fields.many2many('ir.attachment', 'message_attachment_rel', 'message_id', 'attachment_id', 'Attachments'), 
147     }
148
149 mailgate_message()
150
151 class mailgate_tool(osv.osv_memory):
152
153     _name = 'email.server.tools'
154     _description = "Email Server Tools"
155     
156     def _to_decode(self, s, charsets):
157         for charset in charsets:
158             if charset:
159                 try:
160                     return s.decode(charset)
161                 except UnicodeError:
162                     pass
163         return s.decode('latin1')
164
165     def _decode_header(self, text):
166         if text:
167             text = decode_header(text.replace('\r', '')) 
168         return ''.join(map(lambda x:self._to_decode(x[0], [x[1]]), text or []))
169  
170     def to_email(self, text):
171         _email = re.compile(r'.*<.*@.*\..*>', re.UNICODE)
172         def record(path):
173             eml = path.group()
174             index = eml.index('<')
175             eml = eml[index:-1].replace('<', '').replace('>', '')
176             return eml
177
178         bits = _email.sub(record, text)
179         return bits
180     
181     def history(self, cr, uid, model, res_ids, msg, attach, context=None):
182         """This function creates history for mails fetched
183         @param self: The object pointer
184         @param cr: the current row, from the database cursor,
185         @param uid: the current user’s ID for security checks,
186         @param model: OpenObject Model
187         @param res_ids: Ids of the record of OpenObject model created 
188         @param msg: Email details
189         @param attach: Email attachments
190         """
191         if isinstance(res_ids, (int, long)):
192             res_ids = [res_ids]
193
194         msg_pool = self.pool.get('mailgate.message')
195         for res_id in res_ids:
196             msg_data = {
197                         'name': msg.get('subject', 'No subject'), 
198                         'date': msg.get('date') , 
199                         'description': msg.get('body', msg.get('from')), 
200                         'history': True,
201                         'res_model': model, 
202                         'email_cc': msg.get('cc'), 
203                         'email_from': msg.get('from'), 
204                         'email_to': msg.get('to'), 
205                         'message_id': msg.get('message-id'), 
206                         'references': msg.get('references'), 
207                         'res_id': res_id,
208                         'user_id': uid, 
209                         'attachment_ids': [(6, 0, attach)]
210             }
211             msg_id = msg_pool.create(cr, uid, msg_data, context=context)
212         return True
213     
214     def email_send(self, cr, uid, model, res_id, msg, from_email=False, email_default=False):
215         """This function Sends return email on submission of  Fetched email in OpenERP database
216         @param self: The object pointer
217         @param cr: the current row, from the database cursor,
218         @param uid: the current user’s ID for security checks,
219         @param model: OpenObject Model
220         @param res_id: Id of the record of OpenObject model created from the Email details 
221         @param msg: Email details
222         @param email_default: Default Email address in case of any Problem
223         """
224         history_pool = self.pool.get('mailgate.message')
225         model_pool = self.pool.get(model)
226         from_email = from_email or tools.config.get('email_from', None)
227         message = email.message_from_string(tools.ustr(msg).encode('utf-8'))
228         subject = "[%s] %s" %(res_id, message['Subject'])
229         #msg_mails = []
230         #mails = [self._decode_header(message['From']), self._decode_header(message['To'])]
231         #mails += self._decode_header(message.get('Cc', '')).split(',')
232
233         values = {}
234         if hasattr(model_pool, 'emails_get'):
235             values = model_pool.emails_get(cr, uid, [res_id])
236         emails = values.get(res_id, {})
237
238         priority = emails.get('priority', [3])[0]
239         em = emails['user_email'] + emails['email_from'] + emails['email_cc']
240         msg_mails = map(self.to_email, filter(None, em))
241
242         #mm = [self._decode_header(message['From']), self._decode_header(message['To'])]
243         #mm += self._decode_header(message.get('Cc', '')).split(',')
244
245         #msg_mails = map(self.to_email, filter(None, mm))        
246         
247         encoding = message.get_content_charset()
248         message['body'] = message.get_payload(decode=True)
249         if encoding:
250             message['body'] = tools.ustr(message['body'].decode(encoding))
251
252         body = _("""
253 Hello %s,
254         
255     Your Request ID: %s
256
257 Thanks
258
259 -------- Original Message --------        
260 %s
261 """) %(message['From'], res_id, message['body'])
262         res = None
263         try:
264             res = tools.email_send(from_email, msg_mails, subject, body, openobject_id=res_id)
265         except Exception, e:
266             if email_default:
267                 temp_msg = '[%s] %s'%(res_id, message['Subject'])
268                 del message['Subject']
269                 message['Subject'] = '[OpenERP-FetchError] %s' %(temp_msg)
270                 tools.email_send(from_email, email_default, message.get('Subject'), message.get('body'), openobject_id=res_id)
271         return res
272
273     def process_email(self, cr, uid, model, message, attach=True, context=None):
274         """This function Processes email and create record for given OpenERP model 
275         @param self: The object pointer
276         @param cr: the current row, from the database cursor,
277         @param uid: the current user’s ID for security checks,
278         @param model: OpenObject Model
279         @param message: Email details
280         @param attach: Email attachments
281         @param context: A standard dictionary for contextual values"""
282
283         model_pool = self.pool.get(model)
284         if not context:
285             context = {}
286         res_id = False
287         # Create New Record into particular model
288         def create_record(msg):
289             if hasattr(model_pool, 'message_new'):
290                 res_id = model_pool.message_new(cr, uid, msg, context)
291             else:
292                 data = {
293                     'name': msg.get('subject'),
294                     'email_from': msg.get('from'),
295                     'email_cc': msg.get('cc'),
296                     'user_id': False,
297                     'description': msg.get('body'),
298                     'state' : 'draft',
299                 }
300                 data.update(self.get_partner(cr, uid, msg.get('from'), context=context))
301                 res_id = model_pool.create(cr, uid, data, context=context)
302
303                 att_ids = []
304                 if attach:
305                     for attachment in msg.get('attachments', []):
306                         data_attach = {
307                             'name': attachment,
308                             'datas': binascii.b2a_base64(str(attachments.get(attachment))),
309                             'datas_fname': attachment,
310                             'description': 'Mail attachment',
311                             'res_model': model,
312                             'res_id': res_id,
313                         }
314                         att_ids.append(self.pool.get('ir.attachment').create(cr, uid, data_attach))
315
316             return res_id
317
318         history_pool = self.pool.get('mailgate.message')
319
320         # Warning: message_from_string doesn't always work correctly on unicode,
321         # we must use utf-8 strings here :-(
322         msg_txt = email.message_from_string(tools.ustr(message).encode('utf-8'))
323         message_id = msg_txt.get('Message-ID', False)
324         msg = {}
325
326         if not message_id:
327             # Very unusual situation, be we should be fault-tolerant here
328             message_id = time.time()
329             msg_txt['Message-ID'] = message_id
330             _logger.info('Message without message-id, generating a random one: %s', message_id)
331
332         fields = msg_txt.keys()
333         msg['id'] = message_id
334         msg['message-id'] = message_id
335
336         if 'Subject' in fields:
337             msg['subject'] = self._decode_header(msg_txt.get('Subject'))
338
339         if 'Content-Type' in fields:
340             msg['content-type'] = msg_txt.get('Content-Type')
341
342         if 'From' in fields:
343             msg['from'] = self._decode_header(msg_txt.get('From'))
344
345         if 'Delivered-To' in fields:
346             msg['to'] = self._decode_header(msg_txt.get('Delivered-To'))
347
348         if 'Cc' in fields:
349             msg['cc'] = self._decode_header(msg_txt.get('Cc'))
350
351         if 'Reply-To' in fields:
352             msg['reply'] = self._decode_header(msg_txt.get('Reply-To'))
353
354         if 'Date' in fields:
355             msg['date'] = msg_txt.get('Date')
356
357         if 'Content-Transfer-Encoding' in fields:
358             msg['encoding'] = msg_txt.get('Content-Transfer-Encoding')
359
360         if 'References' in fields:
361             msg['references'] = msg_txt.get('References')
362
363         if 'X-Priority' in fields:
364             msg['priority'] = msg_txt.get('X-priority', '3 (Normal)').split(' ')[0]
365
366         if not msg_txt.is_multipart() or 'text/plain' in msg.get('content-type', ''):
367             encoding = msg_txt.get_content_charset()
368             msg['body'] = msg_txt.get_payload(decode=True)
369             if encoding:
370                 msg['body'] = tools.ustr(msg['body'])
371
372         attachments = {}
373         if msg_txt.is_multipart() or 'multipart/alternative' in msg.get('content-type', ''):
374             body = ""
375             counter = 1
376             for part in msg_txt.walk():
377                 if part.get_content_maintype() == 'multipart':
378                     continue
379
380                 encoding = part.get_content_charset()
381
382                 if part.get_content_maintype()=='text':
383                     content = part.get_payload(decode=True)
384                     filename = part.get_filename()
385                     if filename :
386                         attachments[filename] = content
387                     else:
388                         if encoding:
389                             content = unicode(content, encoding)
390                         if part.get_content_subtype() == 'html':
391                             body = tools.html2plaintext(content)
392                         elif part.get_content_subtype() == 'plain':
393                             body = content
394                 elif part.get_content_maintype()=='application' or part.get_content_maintype()=='image' or part.get_content_maintype()=='text':
395                     filename = part.get_filename();
396                     if filename :
397                         attachments[filename] = part.get_payload(decode=True)
398                     else:
399                         res = part.get_payload(decode=True)
400                         if encoding:
401                             res = tools.ustr(res)
402
403                         body += res
404
405             msg['body'] = body
406             msg['attachments'] = attachments
407         res_ids = []
408         new_res_id = False
409         if msg.get('references'):
410             references = msg.get('references')
411             if '\r\n' in references:
412                 references = msg.get('references').split('\r\n')
413             else:
414                 references = msg.get('references').split(' ')
415             for ref in references:
416                 ref = ref.strip()
417                 res_id = tools.misc.reference_re.search(ref)
418                 if res_id:
419                     res_id = res_id.group(1)
420                 else:
421                     res_id = tools.misc.res_re.search(msg['subject'])
422                     if res_id:
423                         res_id = res_id.group(1)
424                 if res_id:
425                     res_id = int(res_id)
426                     res_ids.append(res_id)
427                     model_pool = self.pool.get(model)
428
429                     vals = {}
430                     if hasattr(model_pool, 'message_update'):
431                         model_pool.message_update(cr, uid, [res_id], vals, msg, context=context)
432
433         if not len(res_ids):
434             new_res_id = create_record(msg)
435             res_ids = [new_res_id]
436         # Store messages
437         context.update({'model' : model})
438         if hasattr(model_pool, '_history'):
439             model_pool._history(cr, uid, res_ids, _('Receive'), history=True, 
440                             subject = msg.get('subject'), 
441                             email = msg.get('to'), 
442                             details = msg.get('body'), 
443                             email_from = msg.get('from'), 
444                             message_id = msg.get('message-id'), 
445                             references = msg.get('references', False),
446                             attach = msg.get('attachments', {}).items(), 
447                             context = context)
448         else:
449             self.history(cr, uid, model, res_ids, msg, att_ids, context=context)
450         return new_res_id
451
452     def get_partner(self, cr, uid, from_email, context=None):
453         """This function returns partner Id based on email passed
454         @param self: The object pointer
455         @param cr: the current row, from the database cursor,
456         @param uid: the current user’s ID for security checks
457         @param from_email: email address based on that function will search for the correct
458         """
459         address_pool = self.pool.get('res.partner.address')
460         res = {
461             'partner_address_id': False,
462             'partner_id': False
463         }
464         from_email = self.to_email(from_email)
465         address_ids = address_pool.search(cr, uid, [('email', '=', from_email)])
466         if address_ids:
467             address = address_pool.browse(cr, uid, address_ids[0])
468             res['partner_address_id'] = address_ids[0]
469             res['partner_id'] = address.partner_id.id
470
471         return res
472
473 mailgate_tool()
474
475