[IMP]Improved some improvements.
[odoo/odoo.git] / addons / mail / mail_mail.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2010-today OpenERP SA (<http://www.openerp.com>)
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 import base64
23 import logging
24 import re
25 from urllib import urlencode
26 from urlparse import urljoin
27
28 from openerp import tools
29 from openerp import SUPERUSER_ID
30 from openerp.addons.base.ir.ir_mail_server import MailDeliveryException
31 from openerp.osv import fields, osv
32 from openerp.tools.translate import _
33
34 _logger = logging.getLogger(__name__)
35
36
37 class mail_mail(osv.Model):
38     """ Model holding RFC2822 email messages to send. This model also provides
39         facilities to queue and send new email messages.  """
40     _name = 'mail.mail'
41     _description = 'Outgoing Mails'
42     _inherits = {'mail.message': 'mail_message_id'}
43     _order = 'id desc'
44
45     _columns = {
46         'mail_message_id': fields.many2one('mail.message', 'Message', required=True, ondelete='cascade'),
47         'state': fields.selection([
48             ('outgoing', 'Outgoing'),
49             ('sent', 'Sent'),
50             ('received', 'Received'),
51             ('exception', 'Delivery Failed'),
52             ('cancel', 'Cancelled'),
53         ], 'Status', readonly=True),
54         'auto_delete': fields.boolean('Auto Delete',
55             help="Permanently delete this email after sending it, to save space"),
56         'references': fields.text('References', help='Message references, such as identifiers of previous messages', readonly=1),
57         'email_to': fields.text('To', help='Message recipients (emails)'),
58         'recipient_ids': fields.many2many('res.partner', string='To (Partners)'),
59         'email_cc': fields.char('Cc', help='Carbon copy message recipients'),
60         'body_html': fields.text('Rich-text Contents', help="Rich-text/HTML message"),
61         # Auto-detected based on create() - if 'mail_message_id' was passed then this mail is a notification
62         # and during unlink() we will not cascade delete the parent and its attachments
63         'notification': fields.boolean('Is Notification',
64             help='Mail has been created to notify people of an existing mail.message')
65     }
66
67     def _get_default_from(self, cr, uid, context=None):
68         """ Kept for compatibility
69             TDE TODO: remove me in 8.0
70         """
71         return self.pool['mail.message']._get_default_from(cr, uid, context=context)
72
73     _defaults = {
74         'state': 'outgoing',
75     }
76
77     def default_get(self, cr, uid, fields, context=None):
78         # protection for `default_type` values leaking from menu action context (e.g. for invoices)
79         # To remove when automatic context propagation is removed in web client
80         if context and context.get('default_type') and context.get('default_type') not in self._all_columns['type'].column.selection:
81             context = dict(context, default_type=None)
82         return super(mail_mail, self).default_get(cr, uid, fields, context=context)
83
84     def _get_reply_to(self, cr, uid, values, context=None):
85         """ Return a specific reply_to: alias of the document through message_get_reply_to
86             or take the email_from
87         """
88         # if value specified: directly return it
89         if values.get('reply_to'):
90             return values.get('reply_to')
91         format_name = True  # whether to use a 'Followers of Pigs <pigs@openerp.com' format
92         email_reply_to = None
93
94         ir_config_parameter = self.pool.get("ir.config_parameter")
95         catchall_domain = ir_config_parameter.get_param(cr, uid, "mail.catchall.domain", context=context)
96
97         # model, res_id, email_from: comes from values OR related message
98         model, res_id, email_from = values.get('model'), values.get('res_id'), values.get('email_from')
99         if values.get('mail_message_id'):
100             message = self.pool.get('mail.message').browse(cr, uid, values.get('mail_message_id'), context=context)
101             if message.reply_to:
102                 email_reply_to = message.reply_to
103                 format_name = False
104             if not model:
105                 model = message.model
106             if not res_id:
107                 res_id = message.res_id
108             if not email_from:
109                 email_from = message.email_from
110
111         # if model and res_id: try to use ``message_get_reply_to`` that returns the document alias
112         if not email_reply_to and model and res_id and hasattr(self.pool[model], 'message_get_reply_to'):
113             email_reply_to = self.pool[model].message_get_reply_to(cr, uid, [res_id], context=context)[0]
114         # no alias reply_to -> catchall alias
115         if not email_reply_to:
116             catchall_alias = ir_config_parameter.get_param(cr, uid, "mail.catchall.alias", context=context)
117             if catchall_domain and catchall_alias:
118                 email_reply_to = '%s@%s' % (catchall_alias, catchall_domain)
119
120         # still no reply_to -> reply_to will be the email_from
121         if not email_reply_to and email_from:
122             email_reply_to = email_from
123
124         # format 'Document name <email_address>'
125         if email_reply_to and model and res_id and format_name:
126             emails = tools.email_split(email_reply_to)
127             if emails:
128                 email_reply_to = emails[0]
129             document_name = self.pool[model].name_get(cr, SUPERUSER_ID, [res_id], context=context)[0]
130             if document_name:
131                 # sanitize document name
132                 sanitized_doc_name = re.sub(r'[^\w+.]+', '-', document_name[1])
133                 # generate reply to
134                 email_reply_to = _('"Followers of %s" <%s>') % (sanitized_doc_name, email_reply_to)
135
136         return email_reply_to
137
138     def create(self, cr, uid, values, context=None):
139         # notification field: if not set, set if mail comes from an existing mail.message
140         if 'notification' not in values and values.get('mail_message_id'):
141             values['notification'] = True
142         mail_id = super(mail_mail, self).create(cr, uid, values, context=context)
143
144         # reply_to: if not set, set with default values that require creation values
145         # but delegate after creation because of mail_message.message_id automatic
146         # creation using existence of reply_to
147         if not values.get('reply_to'):
148             reply_to = self._get_reply_to(cr, uid, values, context=context)
149             if reply_to:
150                 self.write(cr, uid, [mail_id], {'reply_to': reply_to}, context=context)
151         return mail_id
152
153     def unlink(self, cr, uid, ids, context=None):
154         # cascade-delete the parent message for all mails that are not created for a notification
155         ids_to_cascade = self.search(cr, uid, [('notification', '=', False), ('id', 'in', ids)])
156         parent_msg_ids = [m.mail_message_id.id for m in self.browse(cr, uid, ids_to_cascade, context=context)]
157         res = super(mail_mail, self).unlink(cr, uid, ids, context=context)
158         self.pool.get('mail.message').unlink(cr, uid, parent_msg_ids, context=context)
159         return res
160
161     def mark_outgoing(self, cr, uid, ids, context=None):
162         return self.write(cr, uid, ids, {'state': 'outgoing'}, context=context)
163
164     def cancel(self, cr, uid, ids, context=None):
165         return self.write(cr, uid, ids, {'state': 'cancel'}, context=context)
166
167     def process_email_queue(self, cr, uid, ids=None, context=None):
168         """Send immediately queued messages, committing after each
169            message is sent - this is not transactional and should
170            not be called during another transaction!
171
172            :param list ids: optional list of emails ids to send. If passed
173                             no search is performed, and these ids are used
174                             instead.
175            :param dict context: if a 'filters' key is present in context,
176                                 this value will be used as an additional
177                                 filter to further restrict the outgoing
178                                 messages to send (by default all 'outgoing'
179                                 messages are sent).
180         """
181         if context is None:
182             context = {}
183         if not ids:
184             filters = [('state', '=', 'outgoing')]
185             if 'filters' in context:
186                 filters.extend(context['filters'])
187             ids = self.search(cr, uid, filters, context=context)
188         res = None
189         try:
190             # Force auto-commit - this is meant to be called by
191             # the scheduler, and we can't allow rolling back the status
192             # of previously sent emails!
193             res = self.send(cr, uid, ids, auto_commit=True, context=context)
194         except Exception:
195             _logger.exception("Failed processing mail queue")
196         return res
197
198     def _postprocess_sent_message(self, cr, uid, mail, context=None):
199         """Perform any post-processing necessary after sending ``mail``
200         successfully, including deleting it completely along with its
201         attachment if the ``auto_delete`` flag of the mail was set.
202         Overridden by subclasses for extra post-processing behaviors.
203
204         :param browse_record mail: the mail that was just sent
205         :return: True
206         """
207         if mail.auto_delete:
208             # done with SUPERUSER_ID to avoid giving large unlink access rights
209             self.unlink(cr, SUPERUSER_ID, [mail.id], context=context)
210         return True
211
212     #------------------------------------------------------
213     # mail_mail formatting, tools and send mechanism
214     #------------------------------------------------------
215
216     # TODO in 8.0(+): maybe factorize this to enable in modules link generation
217     # independently of mail_mail model
218     # TODO in 8.0(+): factorize doc name sanitized and 'Followers of ...' formatting
219     # because it begins to appear everywhere
220
221     def _get_partner_access_link(self, cr, uid, mail, partner=None, context=None):
222         """ Generate URLs for links in mails:
223             - partner is an user and has read access to the document: direct link to document with model, res_id
224         """
225         if partner and partner.user_ids:
226             base_url = self.pool.get('ir.config_parameter').get_param(cr, uid, 'web.base.url')
227             # the parameters to encode for the query and fragment part of url
228             query = {'db': cr.dbname}
229             fragment = {
230                 'login': partner.user_ids[0].login,
231                 'action': 'mail.action_mail_redirect',
232             }
233             if mail.notification:
234                 fragment.update({
235                         'message_id': mail.mail_message_id.id,
236                     })
237             url = urljoin(base_url, "?%s#%s" % (urlencode(query), urlencode(fragment)))
238             return _("""<small>Access your messages and documents <a style='color:inherit' href="%s">in OpenERP</a></small>""") % url
239         else:
240             return None
241
242     def send_get_mail_subject(self, cr, uid, mail, force=False, partner=None, context=None):
243         """ If subject is void and record_name defined: '<Author> posted on <Resource>'
244
245             :param boolean force: force the subject replacement
246             :param browse_record mail: mail.mail browse_record
247             :param browse_record partner: specific recipient partner
248         """
249         if (force or not mail.subject) and mail.record_name:
250             return 'Re: %s' % (mail.record_name)
251         elif (force or not mail.subject) and mail.parent_id and mail.parent_id.subject:
252             return 'Re: %s' % (mail.parent_id.subject)
253         return mail.subject
254
255     def send_get_mail_body(self, cr, uid, mail, partner=None, context=None):
256         """ Return a specific ir_email body. The main purpose of this method
257             is to be inherited to add custom content depending on some module.
258
259             :param browse_record mail: mail.mail browse_record
260             :param browse_record partner: specific recipient partner
261         """
262         body = mail.body_html
263
264         # generate footer
265         link = self._get_partner_access_link(cr, uid, mail, partner, context=context)
266         if link:
267             body = tools.append_content_to_html(body, link, plaintext=False, container_tag='div')
268         return body
269
270     def send_get_email_dict(self, cr, uid, mail, partner=None, context=None):
271         """ Return a dictionary for specific email values, depending on a
272             partner, or generic to the whole recipients given by mail.email_to.
273
274             :param browse_record mail: mail.mail browse_record
275             :param browse_record partner: specific recipient partner
276         """
277         body = self.send_get_mail_body(cr, uid, mail, partner=partner, context=context)
278         subject = self.send_get_mail_subject(cr, uid, mail, partner=partner, context=context)
279         body_alternative = tools.html2plaintext(body)
280
281         # generate email_to, heuristic:
282         # 1. if 'partner' is specified and there is a related document: Followers of 'Doc' <email>
283         # 2. if 'partner' is specified, but no related document: Partner Name <email>
284         # 3; fallback on mail.email_to that we split to have an email addresses list
285         if partner and mail.record_name:
286             sanitized_record_name = re.sub(r'[^\w+.]+', '-', mail.record_name)
287             email_to = [_('"Followers of %s" <%s>') % (sanitized_record_name, partner.email)]
288         elif partner:
289             email_to = ['%s <%s>' % (partner.name, partner.email)]
290         else:
291             email_to = tools.email_split(mail.email_to)
292
293         return {
294             'body': body,
295             'body_alternative': body_alternative,
296             'subject': subject,
297             'email_to': email_to,
298         }
299
300     def send(self, cr, uid, ids, auto_commit=False, raise_exception=False, context=None):
301         """ Sends the selected emails immediately, ignoring their current
302             state (mails that have already been sent should not be passed
303             unless they should actually be re-sent).
304             Emails successfully delivered are marked as 'sent', and those
305             that fail to be deliver are marked as 'exception', and the
306             corresponding error mail is output in the server logs.
307
308             :param bool auto_commit: whether to force a commit of the mail status
309                 after sending each mail (meant only for scheduler processing);
310                 should never be True during normal transactions (default: False)
311             :param bool raise_exception: whether to raise an exception if the
312                 email sending process has failed
313             :return: True
314         """
315         ir_mail_server = self.pool.get('ir.mail_server')
316         for mail in self.browse(cr, SUPERUSER_ID, ids, context=context):
317             try:
318                 # handle attachments
319                 attachments = []
320                 for attach in mail.attachment_ids:
321                     attachments.append((attach.datas_fname, base64.b64decode(attach.datas)))
322                 # specific behavior to customize the send email for notified partners
323                 email_list = []
324                 if mail.email_to:
325                     email_list.append(self.send_get_email_dict(cr, uid, mail, context=context))
326                 for partner in mail.recipient_ids:
327                     email_list.append(self.send_get_email_dict(cr, uid, mail, partner=partner, context=context))
328
329                 # build an RFC2822 email.message.Message object and send it without queuing
330                 res = None
331                 for email in email_list:
332                     msg = ir_mail_server.build_email(
333                         email_from = mail.email_from,
334                         email_to = email.get('email_to'),
335                         subject = email.get('subject'),
336                         body = email.get('body'),
337                         body_alternative = email.get('body_alternative'),
338                         email_cc = tools.email_split(mail.email_cc),
339                         reply_to = mail.reply_to,
340                         attachments = attachments,
341                         message_id = mail.message_id,
342                         references = mail.references,
343                         object_id = mail.res_id and ('%s-%s' % (mail.res_id, mail.model)),
344                         subtype = 'html',
345                         subtype_alternative = 'plain')
346                     res = ir_mail_server.send_email(cr, uid, msg,
347                         mail_server_id=mail.mail_server_id.id, context=context)
348                 if res:
349                     mail.write({'state': 'sent', 'message_id': res})
350                     mail_sent = True
351                 else:
352                     mail.write({'state': 'exception'})
353                     mail_sent = False
354
355                 # /!\ can't use mail.state here, as mail.refresh() will cause an error
356                 # see revid:odo@openerp.com-20120622152536-42b2s28lvdv3odyr in 6.1
357                 if mail_sent:
358                     self._postprocess_sent_message(cr, uid, mail, context=context)
359             except Exception as e:
360                 _logger.exception('failed sending mail.mail %s', mail.id)
361                 mail.write({'state': 'exception'})
362                 if raise_exception:
363                     if isinstance(e, AssertionError):
364                         # get the args of the original error, wrap into a value and throw a MailDeliveryException
365                         # that is an except_orm, with name and value as arguments
366                         value = '. '.join(e.args)
367                         raise MailDeliveryException(_("Mail Delivery Failed"), value)
368                     raise
369
370             if auto_commit == True:
371                 cr.commit()
372         return True