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