[FIX] mail: fixed some translation issues.
[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.osv import fields, osv
31 from openerp.osv.orm import except_orm
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         'mail_server_id': fields.many2one('ir.mail_server', 'Outgoing mail server', readonly=1),
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_from': fields.char('From', help='Message sender, taken from user preferences.'),
59         'email_to': fields.text('To', help='Message recipients'),
60         'email_cc': fields.char('Cc', help='Carbon copy message recipients'),
61         'reply_to': fields.char('Reply-To', help='Preferred response address for the message'),
62         'body_html': fields.text('Rich-text Contents', help="Rich-text/HTML message"),
63
64         # Auto-detected based on create() - if 'mail_message_id' was passed then this mail is a notification
65         # and during unlink() we will not cascade delete the parent and its attachments
66         'notification': fields.boolean('Is Notification')
67     }
68
69     def _get_default_from(self, cr, uid, context=None):
70         this = self.pool.get('res.users').browse(cr, uid, uid, context=context)
71         if this.alias_domain:
72             return '%s@%s' % (this.alias_name, this.alias_domain)
73         elif this.email:
74             return this.email
75         raise osv.except_osv(_('Invalid Action!'), _("Unable to send email, please configure the sender's email address or alias."))
76
77     _defaults = {
78         'state': 'outgoing',
79         'email_from': lambda self, cr, uid, ctx=None: self._get_default_from(cr, uid, ctx),
80     }
81
82     def default_get(self, cr, uid, fields, context=None):
83         # protection for `default_type` values leaking from menu action context (e.g. for invoices)
84         # To remove when automatic context propagation is removed in web client
85         if context and context.get('default_type') and context.get('default_type') not in self._all_columns['type'].column.selection:
86             context = dict(context, default_type=None)
87         return super(mail_mail, self).default_get(cr, uid, fields, context=context)
88
89     def create(self, cr, uid, values, context=None):
90         if 'notification' not in values and values.get('mail_message_id'):
91             values['notification'] = True
92         return super(mail_mail, self).create(cr, uid, values, context=context)
93
94     def unlink(self, cr, uid, ids, context=None):
95         # cascade-delete the parent message for all mails that are not created for a notification
96         ids_to_cascade = self.search(cr, uid, [('notification', '=', False), ('id', 'in', ids)])
97         parent_msg_ids = [m.mail_message_id.id for m in self.browse(cr, uid, ids_to_cascade, context=context)]
98         res = super(mail_mail, self).unlink(cr, uid, ids, context=context)
99         self.pool.get('mail.message').unlink(cr, uid, parent_msg_ids, context=context)
100         return res
101
102     def mark_outgoing(self, cr, uid, ids, context=None):
103         return self.write(cr, uid, ids, {'state': 'outgoing'}, context=context)
104
105     def cancel(self, cr, uid, ids, context=None):
106         return self.write(cr, uid, ids, {'state': 'cancel'}, context=context)
107
108     def process_email_queue(self, cr, uid, ids=None, context=None):
109         """Send immediately queued messages, committing after each
110            message is sent - this is not transactional and should
111            not be called during another transaction!
112
113            :param list ids: optional list of emails ids to send. If passed
114                             no search is performed, and these ids are used
115                             instead.
116            :param dict context: if a 'filters' key is present in context,
117                                 this value will be used as an additional
118                                 filter to further restrict the outgoing
119                                 messages to send (by default all 'outgoing'
120                                 messages are sent).
121         """
122         if context is None:
123             context = {}
124         if not ids:
125             filters = ['&', ('state', '=', 'outgoing'), ('type', '=', 'email')]
126             if 'filters' in context:
127                 filters.extend(context['filters'])
128             ids = self.search(cr, uid, filters, context=context)
129         res = None
130         try:
131             # Force auto-commit - this is meant to be called by
132             # the scheduler, and we can't allow rolling back the status
133             # of previously sent emails!
134             res = self.send(cr, uid, ids, auto_commit=True, context=context)
135         except Exception:
136             _logger.exception("Failed processing mail queue")
137         return res
138
139     def _postprocess_sent_message(self, cr, uid, mail, context=None):
140         """Perform any post-processing necessary after sending ``mail``
141         successfully, including deleting it completely along with its
142         attachment if the ``auto_delete`` flag of the mail was set.
143         Overridden by subclasses for extra post-processing behaviors.
144
145         :param browse_record mail: the mail that was just sent
146         :return: True
147         """
148         if mail.auto_delete:
149             # done with SUPERUSER_ID to avoid giving large unlink access rights
150             self.unlink(cr, SUPERUSER_ID, [mail.id], context=context)
151         return True
152
153     def send_get_mail_subject(self, cr, uid, mail, force=False, partner=None, context=None):
154         """ If subject is void and record_name defined: '<Author> posted on <Resource>'
155
156             :param boolean force: force the subject replacement
157             :param browse_record mail: mail.mail browse_record
158             :param browse_record partner: specific recipient partner
159         """
160         if force or (not mail.subject and mail.model and mail.res_id):
161             return 'Re: %s' % (mail.record_name)
162         return mail.subject
163
164     def send_get_mail_body(self, cr, uid, mail, partner=None, context=None):
165         """ Return a specific ir_email body. The main purpose of this method
166             is to be inherited by Portal, to add a link for signing in, in
167             each notification email a partner receives.
168
169             :param browse_record mail: mail.mail browse_record
170             :param browse_record partner: specific recipient partner
171         """
172         body = mail.body_html
173         # partner is a user, link to a related document (incentive to install portal)
174         if partner and partner.user_ids and mail.model and mail.res_id \
175                 and self.check_access_rights(cr, partner.user_ids[0].id, 'read', raise_exception=False):
176             related_user = partner.user_ids[0]
177             try:
178                 self.pool.get(mail.model).check_access_rule(cr, related_user.id, [mail.res_id], 'read', context=context)
179                 base_url = self.pool.get('ir.config_parameter').get_param(cr, uid, 'web.base.url')
180                 # the parameters to encode for the query and fragment part of url
181                 query = {'db': cr.dbname}
182                 fragment = {
183                     'login': related_user.login,
184                     'model': mail.model,
185                     'id': mail.res_id,
186                 }
187                 url = urljoin(base_url, "?%s#%s" % (urlencode(query), urlencode(fragment)))
188                 text = _("""<p>Access this document <a href="%s">directly in OpenERP</a></p>""") % url
189                 body = tools.append_content_to_html(body, ("<div><p>%s</p></div>" % text), plaintext=False)
190             except except_orm, e:
191                 pass
192         return body
193
194     def send_get_mail_reply_to(self, cr, uid, mail, partner=None, context=None):
195         """ Return a specific ir_email reply_to.
196
197             :param browse_record mail: mail.mail browse_record
198             :param browse_record partner: specific recipient partner
199         """
200         if mail.reply_to:
201             return mail.reply_to
202         email_reply_to = False
203
204         # if model and res_id: try to use ``message_get_reply_to`` that returns the document alias
205         if mail.model and mail.res_id and hasattr(self.pool.get(mail.model), 'message_get_reply_to'):
206             email_reply_to = self.pool.get(mail.model).message_get_reply_to(cr, uid, [mail.res_id], context=context)[0]
207         # no alias reply_to -> reply_to will be the email_from, only the email part
208         if not email_reply_to and mail.email_from:
209             emails = tools.email_split(mail.email_from)
210             if emails:
211                 email_reply_to = emails[0]
212
213         # format 'Document name <email_address>'
214         if email_reply_to and mail.model and mail.res_id:
215             document_name = self.pool.get(mail.model).name_get(cr, SUPERUSER_ID, [mail.res_id], context=context)[0]
216             if document_name:
217                 # sanitize document name
218                 sanitized_doc_name = re.sub(r'[^\w+.]+', '-', document_name[1])
219                 # generate reply to
220                 email_reply_to = _('"Followers of %s" <%s>') % (sanitized_doc_name, email_reply_to)
221
222         return email_reply_to
223
224     def send_get_email_dict(self, cr, uid, mail, partner=None, context=None):
225         """ Return a dictionary for specific email values, depending on a
226             partner, or generic to the whole recipients given by mail.email_to.
227
228             :param browse_record mail: mail.mail browse_record
229             :param browse_record partner: specific recipient partner
230         """
231         body = self.send_get_mail_body(cr, uid, mail, partner=partner, context=context)
232         subject = self.send_get_mail_subject(cr, uid, mail, partner=partner, context=context)
233         reply_to = self.send_get_mail_reply_to(cr, uid, mail, partner=partner, context=context)
234         body_alternative = tools.html2plaintext(body)
235
236         # generate email_to, heuristic:
237         # 1. if 'partner' is specified and there is a related document: Followers of 'Doc' <email>
238         # 2. if 'partner' is specified, but no related document: Partner Name <email>
239         # 3; fallback on mail.email_to that we split to have an email addresses list
240         if partner and mail.record_name:
241             sanitized_record_name = re.sub(r'[^\w+.]+', '-', mail.record_name)
242             email_to = [_('"Followers of %s" <%s>') % (sanitized_record_name, partner.email)]
243         elif partner:
244             email_to = ['%s <%s>' % (partner.name, partner.email)]
245         else:
246             email_to = tools.email_split(mail.email_to)
247
248         return {
249             'body': body,
250             'body_alternative': body_alternative,
251             'subject': subject,
252             'email_to': email_to,
253             'reply_to': reply_to,
254         }
255
256     def send(self, cr, uid, ids, auto_commit=False, recipient_ids=None, context=None):
257         """ Sends the selected emails immediately, ignoring their current
258             state (mails that have already been sent should not be passed
259             unless they should actually be re-sent).
260             Emails successfully delivered are marked as 'sent', and those
261             that fail to be deliver are marked as 'exception', and the
262             corresponding error mail is output in the server logs.
263
264             :param bool auto_commit: whether to force a commit of the mail status
265                 after sending each mail (meant only for scheduler processing);
266                 should never be True during normal transactions (default: False)
267             :param list recipient_ids: specific list of res.partner recipients.
268                 If set, one email is sent to each partner. Its is possible to
269                 tune the sent email through ``send_get_mail_body`` and ``send_get_mail_subject``.
270                 If not specified, one email is sent to mail_mail.email_to.
271             :return: True
272         """
273         ir_mail_server = self.pool.get('ir.mail_server')
274         for mail in self.browse(cr, uid, ids, context=context):
275             try:
276                 # handle attachments
277                 attachments = []
278                 for attach in mail.attachment_ids:
279                     attachments.append((attach.datas_fname, base64.b64decode(attach.datas)))
280                 # specific behavior to customize the send email for notified partners
281                 email_list = []
282                 if recipient_ids:
283                     for partner in self.pool.get('res.partner').browse(cr, SUPERUSER_ID, recipient_ids, context=context):
284                         email_list.append(self.send_get_email_dict(cr, uid, mail, partner=partner, context=context))
285                 else:
286                     email_list.append(self.send_get_email_dict(cr, uid, mail, context=context))
287
288                 # build an RFC2822 email.message.Message object and send it without queuing
289                 for email in email_list:
290                     msg = ir_mail_server.build_email(
291                         email_from = mail.email_from,
292                         email_to = email.get('email_to'),
293                         subject = email.get('subject'),
294                         body = email.get('body'),
295                         body_alternative = email.get('body_alternative'),
296                         email_cc = tools.email_split(mail.email_cc),
297                         reply_to = email.get('reply_to'),
298                         attachments = attachments,
299                         message_id = mail.message_id,
300                         references = mail.references,
301                         object_id = mail.res_id and ('%s-%s' % (mail.res_id, mail.model)),
302                         subtype = 'html',
303                         subtype_alternative = 'plain')
304                     res = ir_mail_server.send_email(cr, uid, msg,
305                         mail_server_id=mail.mail_server_id.id, context=context)
306                 if res:
307                     mail.write({'state': 'sent', 'message_id': res})
308                     mail_sent = True
309                 else:
310                     mail.write({'state': 'exception'})
311                     mail_sent = False
312
313                 # /!\ can't use mail.state here, as mail.refresh() will cause an error
314                 # see revid:odo@openerp.com-20120622152536-42b2s28lvdv3odyr in 6.1
315                 if mail_sent:
316                     self._postprocess_sent_message(cr, uid, mail, context=context)
317             except Exception:
318                 _logger.exception('failed sending mail.mail %s', mail.id)
319                 mail.write({'state': 'exception'})
320
321             if auto_commit == True:
322                 cr.commit()
323         return True