[IMP] use the openerp namespace.
[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 from openerp import tools
25
26 from openerp import SUPERUSER_ID
27 from openerp.osv import fields, osv
28 from openerp.tools.translate import _
29
30 _logger = logging.getLogger(__name__)
31
32
33 class mail_mail(osv.Model):
34     """ Model holding RFC2822 email messages to send. This model also provides
35         facilities to queue and send new email messages.  """
36     _name = 'mail.mail'
37     _description = 'Outgoing Mails'
38     _inherits = {'mail.message': 'mail_message_id'}
39     _order = 'id desc'
40
41     _columns = {
42         'mail_message_id': fields.many2one('mail.message', 'Message', required=True, ondelete='cascade'),
43         'mail_server_id': fields.many2one('ir.mail_server', 'Outgoing mail server', readonly=1),
44         'state': fields.selection([
45             ('outgoing', 'Outgoing'),
46             ('sent', 'Sent'),
47             ('received', 'Received'),
48             ('exception', 'Delivery Failed'),
49             ('cancel', 'Cancelled'),
50         ], 'Status', readonly=True),
51         'auto_delete': fields.boolean('Auto Delete',
52             help="Permanently delete this email after sending it, to save space"),
53         'references': fields.text('References', help='Message references, such as identifiers of previous messages', readonly=1),
54         'email_from': fields.char('From', help='Message sender, taken from user preferences.'),
55         'email_to': fields.text('To', help='Message recipients'),
56         'email_cc': fields.char('Cc', help='Carbon copy message recipients'),
57         'reply_to': fields.char('Reply-To', help='Preferred response address for the message'),
58         'body_html': fields.text('Rich-text Contents', help="Rich-text/HTML message"),
59
60         # Auto-detected based on create() - if 'mail_message_id' was passed then this mail is a notification
61         # and during unlink() we will not cascade delete the parent and its attachments
62         'notification': fields.boolean('Is Notification')
63     }
64
65     def _get_default_from(self, cr, uid, context=None):
66         this = self.pool.get('res.users').browse(cr, uid, uid, context=context)
67         if this.alias_domain:
68             return '%s@%s' % (this.alias_name, this.alias_domain)
69         elif this.email:
70             return this.email
71         raise osv.except_osv(_('Invalid Action!'), _("Unable to send email, please configure the sender's email address or alias."))
72
73     _defaults = {
74         'state': 'outgoing',
75         'email_from': lambda self, cr, uid, ctx=None: self._get_default_from(cr, uid, ctx),
76     }
77
78     def create(self, cr, uid, values, context=None):
79         if 'notification' not in values and values.get('mail_message_id'):
80             values['notification'] = True
81         return super(mail_mail, self).create(cr, uid, values, context=context)
82
83     def unlink(self, cr, uid, ids, context=None):
84         # cascade-delete the parent message for all mails that are not created for a notification
85         ids_to_cascade = self.search(cr, uid, [('notification', '=', False), ('id', 'in', ids)])
86         parent_msg_ids = [m.mail_message_id.id for m in self.browse(cr, uid, ids_to_cascade, context=context)]
87         res = super(mail_mail, self).unlink(cr, uid, ids, context=context)
88         self.pool.get('mail.message').unlink(cr, uid, parent_msg_ids, context=context)
89         return res
90
91     def mark_outgoing(self, cr, uid, ids, context=None):
92         return self.write(cr, uid, ids, {'state': 'outgoing'}, context=context)
93
94     def cancel(self, cr, uid, ids, context=None):
95         return self.write(cr, uid, ids, {'state': 'cancel'}, context=context)
96
97     def process_email_queue(self, cr, uid, ids=None, context=None):
98         """Send immediately queued messages, committing after each
99            message is sent - this is not transactional and should
100            not be called during another transaction!
101
102            :param list ids: optional list of emails ids to send. If passed
103                             no search is performed, and these ids are used
104                             instead.
105            :param dict context: if a 'filters' key is present in context,
106                                 this value will be used as an additional
107                                 filter to further restrict the outgoing
108                                 messages to send (by default all 'outgoing'
109                                 messages are sent).
110         """
111         if context is None:
112             context = {}
113         if not ids:
114             filters = ['&', ('state', '=', 'outgoing'), ('type', '=', 'email')]
115             if 'filters' in context:
116                 filters.extend(context['filters'])
117             ids = self.search(cr, uid, filters, context=context)
118         res = None
119         try:
120             # Force auto-commit - this is meant to be called by
121             # the scheduler, and we can't allow rolling back the status
122             # of previously sent emails!
123             res = self.send(cr, uid, ids, auto_commit=True, context=context)
124         except Exception:
125             _logger.exception("Failed processing mail queue")
126         return res
127
128     def _postprocess_sent_message(self, cr, uid, mail, context=None):
129         """Perform any post-processing necessary after sending ``mail``
130         successfully, including deleting it completely along with its
131         attachment if the ``auto_delete`` flag of the mail was set.
132         Overridden by subclasses for extra post-processing behaviors.
133
134         :param browse_record mail: the mail that was just sent
135         :return: True
136         """
137         if mail.auto_delete:
138             # done with SUPERUSER_ID to avoid giving large unlink access rights
139             self.unlink(cr, SUPERUSER_ID, [mail.id], context=context)
140         return True
141
142     def send_get_mail_subject(self, cr, uid, mail, force=False, partner=None, context=None):
143         """ If subject is void and record_name defined: '<Author> posted on <Resource>'
144
145             :param boolean force: force the subject replacement
146             :param browse_record mail: mail.mail browse_record
147             :param browse_record partner: specific recipient partner
148         """
149         if force or (not mail.subject and mail.model and mail.res_id):
150             return '%s posted on %s' % (mail.author_id.name, mail.record_name)
151         return mail.subject
152
153     def send_get_mail_body(self, cr, uid, mail, partner=None, context=None):
154         """ Return a specific ir_email body. The main purpose of this method
155             is to be inherited by Portal, to add a link for signing in, in
156             each notification email a partner receives.
157
158             :param browse_record mail: mail.mail browse_record
159             :param browse_record partner: specific recipient partner
160         """
161         return mail.body_html
162
163     def send_get_email_dict(self, cr, uid, mail, partner=None, context=None):
164         """ Return a dictionary for specific email values, depending on a
165             partner, or generic to the whole recipients given by mail.email_to.
166
167             :param browse_record mail: mail.mail browse_record
168             :param browse_record partner: specific recipient partner
169         """
170         body = self.send_get_mail_body(cr, uid, mail, partner=partner, context=context)
171         subject = self.send_get_mail_subject(cr, uid, mail, partner=partner, context=context)
172         body_alternative = tools.html2plaintext(body)
173         email_to = [partner.email] if partner else tools.email_split(mail.email_to)
174         return {
175             'body': body,
176             'body_alternative': body_alternative,
177             'subject': subject,
178             'email_to': email_to,
179         }
180
181     def send(self, cr, uid, ids, auto_commit=False, recipient_ids=None, context=None):
182         """ Sends the selected emails immediately, ignoring their current
183             state (mails that have already been sent should not be passed
184             unless they should actually be re-sent).
185             Emails successfully delivered are marked as 'sent', and those
186             that fail to be deliver are marked as 'exception', and the
187             corresponding error mail is output in the server logs.
188
189             :param bool auto_commit: whether to force a commit of the mail status
190                 after sending each mail (meant only for scheduler processing);
191                 should never be True during normal transactions (default: False)
192             :param list recipient_ids: specific list of res.partner recipients.
193                 If set, one email is sent to each partner. Its is possible to
194                 tune the sent email through ``send_get_mail_body`` and ``send_get_mail_subject``.
195                 If not specified, one email is sent to mail_mail.email_to.
196             :return: True
197         """
198         ir_mail_server = self.pool.get('ir.mail_server')
199         for mail in self.browse(cr, uid, ids, context=context):
200             try:
201                 # handle attachments
202                 attachments = []
203                 for attach in mail.attachment_ids:
204                     attachments.append((attach.datas_fname, base64.b64decode(attach.datas)))
205                 # specific behavior to customize the send email for notified partners
206                 email_list = []
207                 if recipient_ids:
208                     for partner in self.pool.get('res.partner').browse(cr, uid, recipient_ids, context=context):
209                         email_list.append(self.send_get_email_dict(cr, uid, mail, partner=partner, context=context))
210                 else:
211                     email_list.append(self.send_get_email_dict(cr, uid, mail, context=context))
212
213                 # build an RFC2822 email.message.Message object and send it without queuing
214                 for email in email_list:
215                     msg = ir_mail_server.build_email(
216                         email_from = mail.email_from,
217                         email_to = email.get('email_to'),
218                         subject = email.get('subject'),
219                         body = email.get('body'),
220                         body_alternative = email.get('body_alternative'),
221                         email_cc = tools.email_split(mail.email_cc),
222                         reply_to = mail.reply_to,
223                         attachments = attachments,
224                         message_id = mail.message_id,
225                         references = mail.references,
226                         object_id = mail.res_id and ('%s-%s' % (mail.res_id, mail.model)),
227                         subtype = 'html',
228                         subtype_alternative = 'plain')
229                     res = ir_mail_server.send_email(cr, uid, msg,
230                         mail_server_id=mail.mail_server_id.id, context=context)
231                 if res:
232                     mail.write({'state': 'sent', 'message_id': res})
233                 else:
234                     mail.write({'state': 'exception'})
235                 mail.refresh()
236                 if mail.state == 'sent':
237                     self._postprocess_sent_message(cr, uid, mail, context=context)
238             except Exception:
239                 _logger.exception('failed sending mail.mail %s', mail.id)
240                 mail.write({'state': 'exception'})
241
242             if auto_commit == True:
243                 cr.commit()
244         return True