mailgate, implement email_send, call it from process_email, rename emails_get to...
[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 message_followers(self, cr, uid, ids, context=None):
54         """ Get a list of emails of the people following this thread
55         """
56         res = {}
57         if isinstance(ids, (str, int, long)):
58             ids = [long(ids)]
59         for thread in self.browse(cr, uid, ids, context=context):
60             l=[]
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 '')
65             res[thread.id] = l
66         return res
67
68     def msg_send(self, cr, uid, id, *args, **argv):
69         raise Exception, _('Method is not implemented')
70
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):
73         """
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"""
84         if context is None:
85             context = {}
86         if attach is None:
87             attach = []
88
89         # The mailgate sends the ids of the cases and not the object list
90
91         if all(isinstance(case_id, (int, long)) for case_id in cases):
92             cases = self.browse(cr, uid, cases, context=context)
93
94         att_obj = self.pool.get('ir.attachment')
95         obj = self.pool.get('mailgate.message')
96
97         for case in cases:
98             data = {
99                 'name': keyword, 
100                 'user_id': uid, 
101                 'model' : case._name, 
102                 'res_id': case.id, 
103                 'date': time.strftime('%Y-%m-%d %H:%M:%S'), 
104                 'message_id': message_id, 
105             }
106             attachments = []
107             if history:
108                 for att in attach:
109                     attachments.append(att_obj.create(cr, uid, {'name': att[0], 'datas': base64.encodestring(att[1])}))
110
111                 data = {
112                     'name': subject or 'History', 
113                     'history': True, 
114                     'user_id': uid, 
115                     'model' : case._name, 
116                     'res_id': case.id,
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)]
129                 }
130             res = obj.create(cr, uid, data, context)
131         return True
132 mailgate_thread()
133
134 class mailgate_message(osv.osv):
135     '''
136     Mailgateway Message
137     '''
138     _name = 'mailgate.message'
139     _description = 'Mailgateway Message'
140     _order = 'id desc'
141     _columns = {
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'), 
159     }
160
161 mailgate_message()
162
163 class mailgate_tool(osv.osv_memory):
164
165     _name = 'email.server.tools'
166     _description = "Email Server Tools"
167
168     def _to_decode(self, s, charsets):
169         if not s:
170             return s
171         for charset in charsets:
172             if charset:
173                 try:
174                     return s.decode(charset)
175                 except UnicodeError:
176                     pass
177         return s.decode('latin1')
178
179     def _decode_header(self, text):
180         if text:
181             text = decode_header(text.replace('\r', '')) 
182         return ''.join(map(lambda x:self._to_decode(x[0], [x[1]]), text or []))
183
184     def to_email(self,text):
185         return re.findall(r'([^ ,<@]+@[^> ,]+)',text)
186
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
196         """
197         if isinstance(res_ids, (int, long)):
198             res_ids = [res_ids]
199
200         msg_pool = self.pool.get('mailgate.message')
201         for res_id in res_ids:
202             msg_data = {
203                         'name': msg.get('subject', 'No subject'), 
204                         'date': msg.get('date') , 
205                         'description': msg.get('body', msg.get('from')), 
206                         'history': True,
207                         'res_model': model, 
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'), 
213                         'res_id': res_id,
214                         'user_id': uid, 
215                         'attachment_ids': [(6, 0, attach)]
216             }
217             msg_id = msg_pool.create(cr, uid, msg_data, context=context)
218         return True
219
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
225         """
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)
231             if encoding:
232                 message['body'] = self._to_decode(message['body'], [encoding])
233             subject = message['Subject']
234
235             from_email = self._decode_header(message['From'])
236
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))
240
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))]
243
244             res = None
245             try:
246                 res = tools.email_send(from_email, message_forward, subject, body, openobject_id=res_id)
247             except Exception, e:
248                 if email_error:
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)
253
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)
264         if not context:
265             context = {}
266         res_id = False
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)
271             else:
272                 data = {
273                     'name': msg.get('subject'),
274                     'email_from': msg.get('from'),
275                     'email_cc': msg.get('cc'),
276                     'user_id': False,
277                     'description': msg.get('body'),
278                     'state' : 'draft',
279                 }
280                 data.update(self.get_partner(cr, uid, msg.get('from'), context=context))
281                 res_id = model_pool.create(cr, uid, data, context=context)
282
283                 att_ids = []
284                 if attach:
285                     for attachment in msg.get('attachments', []):
286                         data_attach = {
287                             'name': attachment,
288                             'datas': binascii.b2a_base64(str(attachments.get(attachment))),
289                             'datas_fname': attachment,
290                             'description': 'Mail attachment',
291                             'res_model': model,
292                             'res_id': res_id,
293                         }
294                         att_ids.append(self.pool.get('ir.attachment').create(cr, uid, data_attach))
295
296             return res_id
297
298         history_pool = self.pool.get('mailgate.message')
299
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)
304         msg = {}
305
306         if not message_id:
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)
311
312         fields = msg_txt.keys()
313         msg['id'] = message_id
314         msg['message-id'] = message_id
315
316         if 'Subject' in fields:
317             msg['subject'] = self._decode_header(msg_txt.get('Subject'))
318
319         if 'Content-Type' in fields:
320             msg['content-type'] = msg_txt.get('Content-Type')
321
322         if 'From' in fields:
323             msg['from'] = self._decode_header(msg_txt.get('From'))
324
325         if 'Delivered-To' in fields:
326             msg['to'] = self._decode_header(msg_txt.get('Delivered-To'))
327
328         if 'Cc' in fields:
329             msg['cc'] = self._decode_header(msg_txt.get('Cc'))
330
331         if 'Reply-To' in fields:
332             msg['reply'] = self._decode_header(msg_txt.get('Reply-To'))
333
334         if 'Date' in fields:
335             msg['date'] = msg_txt.get('Date')
336
337         if 'Content-Transfer-Encoding' in fields:
338             msg['encoding'] = msg_txt.get('Content-Transfer-Encoding')
339
340         if 'References' in fields:
341             msg['references'] = msg_txt.get('References')
342
343         if 'X-Priority' in fields:
344             msg['priority'] = msg_txt.get('X-priority', '3 (Normal)').split(' ')[0]
345
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)
349             if encoding:
350                 msg['body'] = tools.ustr(msg['body'])
351
352         attachments = {}
353         if msg_txt.is_multipart() or 'multipart/alternative' in msg.get('content-type', ''):
354             body = ""
355             counter = 1
356             for part in msg_txt.walk():
357                 if part.get_content_maintype() == 'multipart':
358                     continue
359
360                 encoding = part.get_content_charset()
361
362                 if part.get_content_maintype()=='text':
363                     content = part.get_payload(decode=True)
364                     filename = part.get_filename()
365                     if filename :
366                         attachments[filename] = content
367                     else:
368                         if encoding:
369                             content = unicode(content, encoding)
370                         if part.get_content_subtype() == 'html':
371                             body = tools.html2plaintext(content)
372                         elif part.get_content_subtype() == 'plain':
373                             body = content
374                 elif part.get_content_maintype()=='application' or part.get_content_maintype()=='image' or part.get_content_maintype()=='text':
375                     filename = part.get_filename();
376                     if filename :
377                         attachments[filename] = part.get_payload(decode=True)
378                     else:
379                         res = part.get_payload(decode=True)
380                         if encoding:
381                             res = tools.ustr(res)
382                         body += res
383
384             msg['body'] = body
385             msg['attachments'] = attachments
386         res_ids = []
387         new_res_id = False
388         if msg.get('references'):
389             references = msg.get('references')
390             if '\r\n' in references:
391                 references = msg.get('references').split('\r\n')
392             else:
393                 references = msg.get('references').split(' ')
394             for ref in references:
395                 ref = ref.strip()
396                 res_id = tools.misc.reference_re.search(ref)
397                 if res_id:
398                     res_id = res_id.group(1)
399                 else:
400                     res_id = tools.misc.res_re.search(msg['subject'])
401                     if res_id:
402                         res_id = res_id.group(1)
403                 if res_id:
404                     res_id = int(res_id)
405                     res_ids.append(res_id)
406                     model_pool = self.pool.get(model)
407
408                     vals = {}
409                     if hasattr(model_pool, 'message_update'):
410                         model_pool.message_update(cr, uid, [res_id], vals, msg, context=context)
411
412         if not len(res_ids):
413             new_res_id = create_record(msg)
414             res_ids = [new_res_id]
415         # Store messages
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(),
426                             context = context)
427         else:
428             self.history(cr, uid, model, res_ids, msg, att_ids, context=context)
429         self.email_forward(cr, uid, model, res_ids, message)
430         return new_res_id
431
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
438         """
439         address_pool = self.pool.get('res.partner.address')
440         res = {
441             'partner_address_id': False,
442             'partner_id': False
443         }
444         from_email = self.to_email(from_email)[0]
445         address_ids = address_pool.search(cr, uid, [('email', '=', from_email)])
446         if address_ids:
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
450
451         return res
452
453 mailgate_tool()