0bd15374ee2992e00a8cc7018631b460823d9653
[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     _defaults = {
68         'state': 'outgoing',
69     }
70
71     def default_get(self, cr, uid, fields, context=None):
72         # protection for `default_type` values leaking from menu action context (e.g. for invoices)
73         # To remove when automatic context propagation is removed in web client
74         if context and context.get('default_type') and context.get('default_type') not in self._all_columns['type'].column.selection:
75             context = dict(context, default_type=None)
76         return super(mail_mail, self).default_get(cr, uid, fields, context=context)
77
78     def create(self, cr, uid, values, context=None):
79         # notification field: if not set, set if mail comes from an existing mail.message
80         if 'notification' not in values and values.get('mail_message_id'):
81             values['notification'] = True
82         return super(mail_mail, self).create(cr, uid, values, context=context)
83
84     def unlink(self, cr, uid, ids, context=None):
85         # cascade-delete the parent message for all mails that are not created for a notification
86         ids_to_cascade = self.search(cr, uid, [('notification', '=', False), ('id', 'in', ids)])
87         parent_msg_ids = [m.mail_message_id.id for m in self.browse(cr, uid, ids_to_cascade, context=context)]
88         res = super(mail_mail, self).unlink(cr, uid, ids, context=context)
89         self.pool.get('mail.message').unlink(cr, uid, parent_msg_ids, context=context)
90         return res
91
92     def mark_outgoing(self, cr, uid, ids, context=None):
93         return self.write(cr, uid, ids, {'state': 'outgoing'}, context=context)
94
95     def cancel(self, cr, uid, ids, context=None):
96         return self.write(cr, uid, ids, {'state': 'cancel'}, context=context)
97
98     def process_email_queue(self, cr, uid, ids=None, context=None):
99         """Send immediately queued messages, committing after each
100            message is sent - this is not transactional and should
101            not be called during another transaction!
102
103            :param list ids: optional list of emails ids to send. If passed
104                             no search is performed, and these ids are used
105                             instead.
106            :param dict context: if a 'filters' key is present in context,
107                                 this value will be used as an additional
108                                 filter to further restrict the outgoing
109                                 messages to send (by default all 'outgoing'
110                                 messages are sent).
111         """
112         if context is None:
113             context = {}
114         if not ids:
115             filters = [('state', '=', 'outgoing')]
116             if 'filters' in context:
117                 filters.extend(context['filters'])
118             ids = self.search(cr, uid, filters, context=context)
119         res = None
120         try:
121             # Force auto-commit - this is meant to be called by
122             # the scheduler, and we can't allow rolling back the status
123             # of previously sent emails!
124             res = self.send(cr, uid, ids, auto_commit=True, context=context)
125         except Exception:
126             _logger.exception("Failed processing mail queue")
127         return res
128
129     def _postprocess_sent_message(self, cr, uid, mail, context=None):
130         """Perform any post-processing necessary after sending ``mail``
131         successfully, including deleting it completely along with its
132         attachment if the ``auto_delete`` flag of the mail was set.
133         Overridden by subclasses for extra post-processing behaviors.
134
135         :param browse_record mail: the mail that was just sent
136         :return: True
137         """
138         if mail.auto_delete:
139             # done with SUPERUSER_ID to avoid giving large unlink access rights
140             self.unlink(cr, SUPERUSER_ID, [mail.id], context=context)
141         return True
142
143     #------------------------------------------------------
144     # mail_mail formatting, tools and send mechanism
145     #------------------------------------------------------
146
147     def _get_partner_access_link(self, cr, uid, mail, partner=None, context=None):
148         """ Generate URLs for links in mails:
149             - partner is an user and has read access to the document: direct link to document with model, res_id
150         """
151         if partner and partner.user_ids:
152             base_url = self.pool.get('ir.config_parameter').get_param(cr, uid, 'web.base.url')
153             # the parameters to encode for the query and fragment part of url
154             query = {'db': cr.dbname}
155             fragment = {
156                 'login': partner.user_ids[0].login,
157                 'action': 'mail.action_mail_redirect',
158             }
159             if mail.notification:
160                 fragment['message_id'] = mail.mail_message_id.id
161             elif mail.model and mail.res_id:
162                 fragment.update(model=mail.model, res_id=mail.res_id)
163
164             url = urljoin(base_url, "/web?%s#%s" % (urlencode(query), urlencode(fragment)))
165             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
166         else:
167             return None
168
169     def send_get_mail_subject(self, cr, uid, mail, force=False, partner=None, context=None):
170         """ If subject is void and record_name defined: '<Author> posted on <Resource>'
171
172             :param boolean force: force the subject replacement
173             :param browse_record mail: mail.mail browse_record
174             :param browse_record partner: specific recipient partner
175         """
176         if (force or not mail.subject) and mail.record_name:
177             return 'Re: %s' % (mail.record_name)
178         elif (force or not mail.subject) and mail.parent_id and mail.parent_id.subject:
179             return 'Re: %s' % (mail.parent_id.subject)
180         return mail.subject
181
182     def send_get_mail_body(self, cr, uid, mail, partner=None, context=None):
183         """ Return a specific ir_email body. The main purpose of this method
184             is to be inherited to add custom content depending on some module.
185
186             :param browse_record mail: mail.mail browse_record
187             :param browse_record partner: specific recipient partner
188         """
189         body = mail.body_html
190
191         # generate footer
192         link = self._get_partner_access_link(cr, uid, mail, partner, context=context)
193         if link:
194             body = tools.append_content_to_html(body, link, plaintext=False, container_tag='div')
195         return body
196
197     def send_get_email_dict(self, cr, uid, mail, partner=None, context=None):
198         """ Return a dictionary for specific email values, depending on a
199             partner, or generic to the whole recipients given by mail.email_to.
200
201             :param browse_record mail: mail.mail browse_record
202             :param browse_record partner: specific recipient partner
203         """
204         body = self.send_get_mail_body(cr, uid, mail, partner=partner, context=context)
205         subject = self.send_get_mail_subject(cr, uid, mail, partner=partner, context=context)
206         body_alternative = tools.html2plaintext(body)
207
208         # generate email_to, heuristic:
209         # 1. if 'partner' is specified and there is a related document: Followers of 'Doc' <email>
210         # 2. if 'partner' is specified, but no related document: Partner Name <email>
211         # 3; fallback on mail.email_to that we split to have an email addresses list
212         if partner and mail.record_name:
213             sanitized_record_name = re.sub(r'[^\w+.]+', '-', mail.record_name)
214             email_to = [_('"Followers of %s" <%s>') % (sanitized_record_name, partner.email)]
215         elif partner:
216             email_to = ['%s <%s>' % (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, uid, 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                     res = ir_mail_server.send_email(cr, uid, msg,
289                                                     mail_server_id=mail.mail_server_id.id,
290                                                     context=context)
291
292                 if res:
293                     mail.write({'state': 'sent', 'message_id': res})
294                     mail_sent = True
295                 else:
296                     mail.write({'state': 'exception'})
297                     mail_sent = False
298
299                 # /!\ can't use mail.state here, as mail.refresh() will cause an error
300                 # see revid:odo@openerp.com-20120622152536-42b2s28lvdv3odyr in 6.1
301                 if mail_sent:
302                     _logger.info('Mail with ID %r and Message-Id %r successfully sent', mail.id, mail.message_id)
303                     self._postprocess_sent_message(cr, uid, mail, context=context)
304             except MemoryError:
305                 # prevent catching transient MemoryErrors, bubble up to notify user or abort cron job
306                 # instead of marking the mail as failed
307                 _logger.exception('MemoryError while processing mail with ID %r and Msg-Id %r. '\
308                                       'Consider raising the --limit-memory-hard startup option',
309                                   mail.id, mail.message_id)
310                 raise
311             except Exception as e:
312                 _logger.exception('failed sending mail.mail %s', mail.id)
313                 mail.write({'state': 'exception'})
314                 if raise_exception:
315                     if isinstance(e, AssertionError):
316                         # get the args of the original error, wrap into a value and throw a MailDeliveryException
317                         # that is an except_orm, with name and value as arguments
318                         value = '. '.join(e.args)
319                         raise MailDeliveryException(_("Mail Delivery Failed"), value)
320                     raise
321
322             if auto_commit == True:
323                 cr.commit()
324         return True